2017-09-28 57 views
-2

這裏沒有粘貼整個代碼,該行是:的PrintWriter:java.io.FileNotFoundException:在異常情況持續發生,系統找不到指定的路徑

PrintWriter prtwrt = new PrintWriter(new File(directoryName+File.separator+stud.getIndex()+".txt")); 

我已經諮詢了互聯網和書籍我對Java有所瞭解,並且應該遵循所有邏輯工作,但事實並非如此。有人可以解釋爲什麼它不起作用,或者可能提出解決方案嗎?

堆棧跟蹤:

java.io.FileNotFoundException: students\0096-03.txt (The system cannot find the path specified) 
    at java.io.FileOutputStream.open0(Native Method) 
    at java.io.FileOutputStream.open(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at java.io.FileWriter.<init>(Unknown Source) 
    at StudentsManager.main(StudentsManager.java:47) 
    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 edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267) 

此外,目錄名,顧名思義,是該文件應該創建目錄的名稱。在這種情況下,它是「學生」。

+3

什麼是'directoryName'?也可以使用堆棧跟蹤粘貼整個異常 – Antoniossss

+0

它不起作用,因爲系統找不到指定的路徑。 – Oleg

+0

@Antoniossss編輯了問題 –

回答

0

嘗試輸入文件的完整路徑,因爲您可能會輸入相對路徑。

如果你想檢查是否已找到該文件試試下面的代碼:

File file = new File(...); 
if(!file.exists()) { 
    System.out.println("File not found!"); 
    return; 
} 
0

所以讓有

File f=new File(directoryName+File.separator+stud.getIndex()+".txt"); 

首先讓檢查,如果路徑存在,如果它創建目錄樹沒有:

if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); 

現在你可以嘗試創建作家

PrintWriter prtwrt = new PrintWriter(f); 

PrintWriter如果還不存在,應該創建新文件;如果因爲某些原因無法正常工作,請在創建文件之前使用f.createNewFile()

總而言之,它必須工作。

相關問題