0

Here is my scenario.

I have MainActivity.java in which I am calling the thread like this

private void callXMLParserThread() {

    String filePath = "file:///android_asset/weather_conditions.xml";
    parserThread = new XMLParserThread(context, filePath);
    parserThread.start();

}

and here is my XMLParserThread.java

public class XMLParserThread extends Thread {

Context context;
String fileName;
XMLParser xmlParser;

public XMLParserThread(Context context, String fileName) {

    this.context = context;
    this.fileName = fileName;
}

@Override
public void run() {

    xmlParser = new XMLParser();

    String xmlResponse = null;
    try {
        xmlResponse = xmlParser.getXmlFromFile(context, fileName);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Log.d("xmlResponse", xmlResponse + "");

    super.run();
}

}

Notice: In run() method I'm calling the another method getXmlFromFile() resides in XMLParser.java

Now here is my getXmlFromFile() method.

public String getXmlFromFile(Context context, String fileName) throws IOException {

    Log.e("fileName", fileName);

    InputStream is = null;
    try {
        is = context.getAssets().open(fileName);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      buf.write(b);
      result = bis.read();
    }        
    return buf.toString();
}

Problem

When I execute the code it throws the java.io.FileNotFoundException: file:///android_asset/weather_conditions.xml at xml.parser.XMLParser.getXmlFromFile(XMLParser.java:43)

where the line no 43 is is = context.getAssets().open(fileName); in my getXmlFromFile() method

Also, I'm sure the file exists in the assets folder. Where am I making a mistake?

4

2 回答 2

1

当您从资产定义路径时,只写资产子文件夹的路径。

如果您有以下 xml 文件:

assets/android_asset/weather_conditions.xml

所以文件路径应该是:

String filePath = "android_asset/weather_conditions.xml";

顺便说一句,您的代码中有助手:

is = context.getAssets().open(fileName);

context.getAssets()表示打开assets文件夹并在那里找到路径。

于 2013-09-19T07:59:38.693 回答
0

如果我没记错的话,您可以在没有“file:///...”部分的情况下说如下。

String filePath = "weather_conditions.xml";
于 2013-09-19T07:59:36.973 回答