我正在研究一項功能,使用戶能夠檢查單個學生的評估結果。我使用try和catch,但是當我運行代碼時,系統直接運行到catch部分,並且文件的內容是空白的。我不確定這個問題的原因。這裏是我的代碼:無法在java中編寫txt文件
System.out.println('\n' + "Please enter the Student's uni that you would like to call. Type 'exit' to leave");
String studentInfo = s.nextLine();
if (studentInfo.equalsIgnoreCase("exit")) {
userSelection = "exit";
}
boolean studentFound = false;
for (int i = 0; i < students.size(); i++) {
if (studentInfo.equalsIgnoreCase(students.get(i).getStudentUI())) {
studentFound = true;
try {
File singleStudentList = new File(studentInfo + " .txt");
PrintWriter writer = new PrintWriter(singleStudentList);
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
writer.close();
} catch (Exception e) {
System.out.println("Problem writing the file. Please make sure the path is correct");
}
}
}
感謝您的幫助!
您不打印出異常消息! e.printStackTrace()。打印出來,編輯問題,並顯示堆棧跟蹤。 – OldProgrammer
如果您的代碼正在直接進入catch,那麼問題可能出在File或PrintWriter的構造函數之一上。查看文檔以查看它們拋出的特定異常:https://docs.oracle.com/javase/8/docs/api/java/io/File.html#File-java.lang.String- https: //docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#PrintWriter-java.io.File- 據我的經驗,問題可能是你試圖打開的文件doesn 't exists – Antiphon0x
使用'System.out.println(singleStudentList.getCanonicalPath())'來顯示它正在嘗試使用的文件路徑。有可能你的程序沒有在正確的目錄中查找。 –