2015-01-13 80 views
3

我開發一個Android應用程序,在主要活動我想用下面的代碼行列出特定包中的所有文件:列出文件返回null

String[] files = new File("src/com/android/app/").list(); 

,則返回null !?有什麼不對 ? 謝謝。

+0

@Kon:我用的是相同的語法在Java SE應用程序和它的作品,我認爲有些事情相對於應用程序的結構在Android設備安裝(APK)時 – user3728064

+0

'的src/COM /安卓/ app /'在Android應用程序項目中建議文件,特別是Java源代碼目錄。這在運行時不會作爲任何目錄中文件系統上的文件存在,更不用說在您嘗試使用的破損目錄中。 – CommonsWare

+0

@CommonsWare你是對的,我想知道如何在APK文件中表示項目結構! – user3728064

回答

0

我解決了這個問題,同時所有的Dalvik虛擬機編譯的類都要使用DexFile類Dex File documentation

public List<String> getClasses(Context context, String package) { 
    List<String> classes = new LinkedList<String>(); 
    try { 
     DexFile dexFile = new DexFile(context.getPackageCodePath()); 
      for (Enumeration<String> iter = dexFile.entries(); iter.hasMoreElements();) { 
       String currentClass = iter.nextElement(); 
        if (currentClass.contains(package)) { 
          classes.add(currentClass); 
        } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    return classes; 
} 
2

JavadocsFile類:

用戶界面和操作系統使用與系統相關的路徑名 字符串來命名文件和目錄。該課程提供了一個 抽象的,與系統無關的分層路徑名稱視圖。一個 抽象路徑名有兩個組件:

An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX root directory, or "\\\\" for a Microsoft Windows UNC pathname, and 
A sequence of zero or more string names. 

所以你缺少前綴字符串,它似乎。換句話說,路徑名不是相對的,它是絕對的。

+0

我使用了'System.getProperty(「file.separator」)'但徒勞無功,我得到了同樣的錯誤,我認爲這個項目APK文件打包時更改結構。我也試過'String [] files = new File(「src/com/android/app /」)。list();''''''''''我在文件array:config,cache,acct,vendor,d中得到了這個。 。,數據,根,開發。現在我試圖瞭解APK文件的結構以檢索編譯類的路徑 – user3728064

+0

您引用的語句表示前綴是可選的,因此它不能'丟失',並且您完全錯過了真正的問題。 – EJP