【发布时间】:2015-03-11 20:53:45
【问题描述】:
我正在尝试在 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。
【问题讨论】:
-
试试
City.class.getResourceAsStream(locations_file_path)); -
@Marcus 同样的问题
-
嗯.. 我看不出您的代码有任何问题。您是否尝试过清理项目?
-
阅读它们,但 logcat 确实指出这行代码会导致错误。另外,清理了项目@Marcus