2011-10-19 40 views
0

我正在使用Eclipse。有人知道這段代碼試圖從哪裏獲取文件嗎? 我已將我的文件複製到項目文件夾以及srr/package_path文件夾中。Android加載本地xml文件

public String getFromFile(ASerializer aserializer) { 
    String data = new String(); 
    try { 
    FileInputStream stream = new FileInputStream(new File(aserializer.toLocalResource())); 
     FileChannel fc = stream.getChannel(); 
     MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); 
     /* Instead of using default, pass in a decoder. */ 
     data = Charset.defaultCharset().decode(bb).toString(); 
     stream.close(); 
    } 
    catch (Exception e){ 
     data = "File not found"; 
    } 
    return data; 
} 
+0

請提供有關'ASerializer'類的更多信息 –

+0

序列化程序只返回文件名。我只是不知道getFromFile在看什麼。什麼是defaulr文件夾? – iCantSeeSharp

回答

1

該代碼因爲使用FileInputStream而將文件路徑解釋爲整個Android文件系統上的文件路徑。也就是說,文件系統根將成爲整個Android系統所駐留的文件系統的根,而不是您的應用程序資源中的某處。

如果要基於文件名從應用程序資源加載的文件,可以把文件在Eclipse應用程序項目的「資產」的目錄,然後使用:

InputStream inputStream = getResources().getAssets().open("file.xml"); 

得到一個InputStream要使用的文件。給予AssetManager.open()的路徑是相對於'資產'目錄。您也可以組織子目錄中的文件:

InputStream inputStream = getResources().getAssets().open("subdirectory/file.xml"); 
+0

在資產文件夾中,我不得不將.xml文件重命名爲.txt,因爲程序會解析它們的內容,但無論如何,這是移動它們的地方,謝謝! – iCantSeeSharp

+0

請參閱https://stackoverflow.com/questions/2856407/android-how-to-get-access-to-raw-resources-that-i-put-in-res-folder/2856501#2856501 – fangzhzh

0

我認爲它無論是資產的文件夾或res文件夾 我會建議使用DDMS文件瀏覽器找到確切位置

在Eclipse中去DDMS中。有一次去的文件瀏覽器選項卡 您應該在數據/數據/包名中找到您的應用程序(可能稍微偏離這是來自內存)搜索包名中的文件夾