我正在嘗試向信息寫入文件時遇到NullPointerException。任何人都可以幫我看看發生了什麼問題嗎?寫入文件java錯誤
else if(response == 4){
System.out.println("Enter the name of the file to save items to: ");
saveFile = input.nextLine();
try {outfile = new PrintWriter(new FileWriter(saveFile+".txt"));}
catch (IOException err) {
outfile = null;
System.out.println("Error writing to file\n");
}
for (int i = 0; i < items.length; i++) {
outfile.print(items[i].getType() + "\n" + items[i].getName() + "\n" + items[i].getDescription() + "\n" + items[i].getCalories() + "\n" + items[i].getItemSpecifics());
}
這是什麼行'outfile = null;'在做什麼? –
你需要在'outfile.print'之前檢查'outfile' –
在我看來,你想把'for'循環放在'try'塊中。這樣,如果在初始化'outfile'時引發異常,它將不會被執行。 – Onyxite