我有一个问题,我的 android 应用程序的一部分在 android 版本 4.1.2 上工作正常,但在 android 4.4.3 上执行同一部分时抛出 NullPointerException。我的最小 sdk 设置为 15,目标 sdk 为 21。请查找以下代码:
try {
FileInputStream towe = new FileInputStream(path2);
re = new BufferedReader(new InputStreamReader(towe));
while ((res = re.readLine()) != null) {
result.append(res);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
re.close(); //ERROR IS GENERATED AT THIS LINE
} catch (IOException e) {
e.printStackTrace();
}
}
各位早上好,好久不见了。事实证明,由于文件路径而引发了异常。我对 android 4.1.2 的路径进行了硬编码,但在 4.4.3 中,即使设备相同,该路径也是不同的。我最终使用了
一个ndroid.os.Environment.getExternalStorageDirectory();
方法。现在两者都工作得很好。感谢您的建议
最佳答案
从多个角度来看,这是正确的写法:
try (FileInputStream towe = new FileInputStream(path2);
Reader re = new BufferedReader(new InputStreamReader(towe))) {
while ((res = re.readLine()) != null) {
result.append(res);
}
}
- 使用尝试资源。它更简单、更简洁。
- 不要捕获异常,并像什么都没发生一样继续。如果您发现自己这样做,那么您可能在错误的位置捕获了异常。
- 在随机位置打印堆栈跟踪不是一个好主意。
如果您不使用try-with-resources,那么您需要在finally
block 中测试re
是否为非空以避免 NPE。它看起来像这样,删除了错误的堆栈跟踪和异常压缩。
try {
FileInputStream towe = new FileInputStream(path2);
re = new BufferedReader(new InputStreamReader(towe));
while ((res = re.readLine()) != null) {
result.append(res);
}
} finally {
if (re != null) {
re.close();
}
}
即使如此,理论上也存在 towe
不会关闭的风险。 (提示:Error
子类。)
NullPointerException on android 4.4.3 but not 4.1.2
这最有可能意味着 new FileInputStream(path2);
在一个平台上抛出异常(可能是某种 IOException
),而不是在另一个平台上。线索很可能在 I/O 异常的消息中。
关于java - Android 4.4.3 上出现 NullPointerException,但 4.1.2 上没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36794506/