我正在尝试在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中给出的错误是
IllegalArgumentException
中的DocumentBuilder.parse(...)
,因为City.class.getClassLoader().getResourceAsStream("locations.xml"))
返回null
。 最佳答案
我认为您需要验证最终apk文件中的xml文件实际上是否包含在您认为的位置。
Android的更常见模式是将文件放在“ assets”目录中,然后使用Activity的getAssets()方法从该目录加载文件。
见Read Assets file as string