[英]Android load file from classpath causing crash
我正在尝试在Android的静态上下文中从类路径加载文件,SO上的每个类似问题都建议使用MyClass.class.getClassLoader().getResourcesAsStream(<filepath>)
,但这会导致我的应用在崩溃之前崩溃打开。
我的目标SDK是19,最低SDK级别是17,并且我正在使用运行Android Lollipop的手机
这是我尝试加载文件“ locations.xml”的代码部分:
public static final String LOCATIONS_FILE_PATH = "locations.xml";
public static ArrayList<City> getLocations(String locations_file_path) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(
City.class.getClassLoader().getResourceAsStream(locations_file_path));
该文件与引用它的java类位于同一包中。
logcat中给出的错误是DocumentBuilder.parse(...)
的IllegalArgumentException
,因为City.class.getClassLoader().getResourceAsStream("locations.xml"))
返回null
。
我认为您需要验证最终apk文件中的xml文件实际上是否包含在您认为的位置。
Android的更常见模式是将文件放在“ assets”目录中,然后使用Activity的getAssets()方法从该目录加载文件。
作为getResourceAsStream
的替代方法,您可以按照本教程中的说明使用FileInputStream
请注意 ,如果FileInputStream
还返回null
,那么很有可能像@GreyBeardedGeek所说的那样,实际上在最终apk文件中不包含xml文件。
相关代码:
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DocumentBuilderDemo {
public static void main(String[] args) {
// create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// create a new document from input stream
FileInputStream fis = new FileInputStream("Student.xml");
Document doc = builder.parse(fis);
// get the first element
Element element = doc.getDocumentElement();
// get all child nodes
NodeList nodes = element.getChildNodes();
// print the text content of each child
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("" + nodes.item(i).getTextContent());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Student.xml(在您的情况下为locations.xml)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="10">
<age>12</age>
<name>Malik</name>
</student>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.