我尝试从文件中反序列化数据,但遇到了 FileNotFoundException。在程序启动时,.cycles
文件并不存在。
Cycles сl;
try {
сl = Cycles.deserialize();
logger.info("The Cycles object was successfully deserialized");
} catch (IOException e2) {
logger.info("The Cycles object was not detected");
...
上述日志均未输出。
public static Cycles deserialize() throws IOException {
FileInputStream fileIn = null;
ObjectInputStream in = null;
try {
fileIn = new FileInputStream(
System.getProperty("user.home") + System.getProperty("file.separator") + ".cycles");
in = new ObjectInputStream(fileIn);
return (Cycles) in.readObject();
} catch (IOException i) {
i.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} finally {
in.close();
fileIn.close();
}
}
IOException 类确实包含了 FileNotFoundException,因此在捕获 IOException 时,理论上可以处理 FileNotFoundException 异常。我原本预期在这个方法中会得到 null 返回值,但实际上程序却出现了崩溃。
java.io.FileNotFoundException: C:\Users\activeUser\.cycles (The specified file cannot be found)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at main.Cycles.deserialize(Cycles.java:56)
at main.FirefoxHeadlessServer.main(FirefoxHeadlessServer.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:61)
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:61)
Caused by: java.lang.NullPointerException
at main.Cycles.deserialize(Cycles.java:67)
at main.FirefoxHeadlessServer.main(FirefoxHeadlessServer.java:141)
... 5 more