我想知道如何使它成爲我的程序創建一個文件,如果它尚未找到它?如何避免FileNotFoundException?
public void load() throws Exception {
try
{
File log = new File(FILE_NAME); //opens the file
FileInputStream fileIn = new FileInputStream(log);
ObjectInputStream in = new ObjectInputStream(fileIn); //de-serializes
videosList = (ArrayList)in.readObject(); // de-serializes
in.close(); //closes the file
fileIn.close();
} catch(Exception i)
{
i.printStackTrace();
}
這是我收到的錯誤:
java.io.FileNotFoundException: Users/hanaezz/Desktop/output.ser (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at videostore.BinaryFile.load(BinaryFile.java:31)
at videostore.VideoStore.<init>(VideoStore.java:33)
at videostore.VideoStore$6.run(VideoStore.java:430)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
所有多餘的東西存在,因爲我的程序也是一個GUI程序。然後我也有一個方法,它應該寫我的對象到一個文件...
public void writeToFile() throws Exception{
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(videosList);
oos.close();
outputStream.close();
}
這會引發相同的異常。我怎樣才能避免這種情況?我不知道如何修改FIS/OIS來創建文件,如果他們沒有找到它..或者我認爲它會更有效率的FOS/OOS做到這一點呢?
錯誤,請不要試圖打開一個不存在的文件?在這種情況下,你似乎缺少文件名中的前導'/'。 – EJP
可能重複[檢查文件是否存在java](http://stackoverflow.com/questions/1237235/check-file-exists-java) – Ducaz035
@ Ducaz035絕對不是。這是關於附加到現有文件。 – EJP