【问题标题】:How to get the filename as string if the file is under the assets directory?如果文件位于资产目录下,如何将文件名作为字符串获取?
【发布时间】:2012-10-04 07:46:10
【问题描述】:
  • 我在资产目录 (com.android.project\assets\xml\file.xml) 下有 xml 文件。
  • 我想调用一个(以下)函数来读取 xml 文件并将内容作为字符串返回。
  • 该函数需要文件的path 作为字符串。我不知道如何将文件的路径作为字符串给出。

    private String getXML(String path){
    
      String xmlString = null;
    
      AssetManager am = this.getAssets();
      try {
        InputStream is = am.open(path);
        int length = is.available();
        byte[] data = new byte[length];
        is.read(data);
        xmlString = new String(data);
      } catch (IOException e1) {
          e1.printStackTrace();
      }
    
      return xmlString;
    }
    

文件.xml:

    <Items>
        <ItemData>
            <ItemNumber>ABC</ItemNumber>
            <Description>Desc1</Description>        
            <Price>9.95</Price>        
            <Weight>10.00</Weight>    
        </ItemData>    
        <ItemData>        
            <ItemNumber>XYZ</ItemNumber>        
            <Description>"Desc2"</Description>        
            <Price>19.95</Price>
            <Weight>22.22</Weight>
        </ItemData>
    </Items>

问题:

  • 如果我的文件位于 \assets\xml\file.xml 下,我如何使用路径作为字符串参数调用函数 getXML(String path)?

  • 最后,有没有更好的方法将 XML 文件作为字符串读取?

谢谢!

【问题讨论】:

  • 我尝试使用像 /assets/xml/file.xml 这样的字符串以及使用反斜杠和正斜杠的许多类似字符串。
  • 看起来你需要弄清楚你的工作目录是什么以及你的文件的相对路径是什么。
  • 使用:file:///android_asset/xml/file.xml
  • 谢谢 njzk2,xml/file.xml 工作。

标签: java android android-xml


【解决方案1】:

以下方法可行:

InputStream is = context.getAssets().open("xml/file.xml");

【讨论】:

  • 错误答案!根据问题,正确的方法是xml/file.xml NOT file.xml。还是谢谢。
  • 感谢 saafh 的更正。希望你得到解决方案.. :)
【解决方案2】:

路径就是使用正斜杠 (/) 的 assets 目录下的路径

因此 assets/x/y.z 被引用为 this.getAssets().open("x/y.z");

这不是读取数据的正确方法 - Inputstream.read 并不保证读取它返回读取的字节数的所有数据 - 这可能适用于较小的文件,但您可能会遇到较大的问题。

这是我用来读取文本文件的通用代码,而不是 FileReader 使用 InputStreamReader

StringBuilder sw = new StringBuilder();
BufferedReader reader = new BufferedReader( new FileReader(file));
String readline = "";
while ((readline = reader.readLine()) != null) { 
    sw.append(readline);
}
String string = sw.toString();

【讨论】:

  • 谢谢你,我现在试试这段代码。你是想说“而不是 InputStreamReader 用户 Filereader?还是最后一句话让我很困惑。
  • 什么是“文件”?在当前情况下,我如何初始化“文件”?
  • new BufferedReader(new InputStreamReader(is));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 2012-01-18
  • 2015-03-03
  • 2018-04-22
  • 2015-11-25
  • 2014-09-12
  • 1970-01-01
相关资源
最近更新 更多