Android加载本地xml文件

问题描述:

我正在使用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

该代码因为使用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://*.com/questions/2856407/android-how-to-get-access-to-raw-resources-that-i-put-in-res-folder/2856501#2856501 – fangzhzh

我认为它无论是资产的文件夹或res文件夹 我会建议使用DDMS文件浏览器找到确切位置

在Eclipse中去DDMS中。有一次去的文件浏览器选项卡 您应该在数据/数据/包名中找到您的应用程序(可能稍微偏离这是来自内存)搜索包名中的文件夹