try{
Writer rwrite = new BufferedWriter(new FileWriter(file, true));
rwrite.append(reservation.toString() + "\n");
rwrite.close();
}
catch(IOException e){
System.out.println("Could not open BufferedWriter.");
e.printStackTrace();
}
我的意思是,基本上我的问题是我无法写入空的csv文件的第一行。我可以写第二个就好。也就是说,如果我自己手动输入了第一行,则可以写第二行。
任何人都可以帮助赞赏的人们,真的,很高兴。我很困惑。
更新:
try{
File file = new File("reservations.csv");
Scanner fileIn = new Scanner(file);
try {
if(fileIn.hasNext()){
PrintWriter printWriter = new PrintWriter(new FileWriter("reservations.csv", true));
printWriter.write(reservation.toString() + "\n");
printWriter.close();
}
if(!fileIn.hasNext()){
PrintWriter printWriter = new PrintWriter(new FileWriter("reservations.csv"));
printWriter.write(reservation.toString() + "\n");
printWriter.close();
}
} catch (IOException e) {
System.out.println("Could not open BufferedWriter.");
e.printStackTrace();
}
}
catch(IOException e){
System.out.println("Error: failed to read from: " + "reservations.csv");
e.printStackTrace();
}
我将代码更改为此,并且此方法可行,但对我来说似乎有点怪异哈哈。无论如何,感谢您的帮助,仍会继续阅读。
尝试一下:-
try (PrintWriter printWriter = new PrintWriter(new FileWriter(file, true))) {
printWriter.write(reservation.toString());
} catch (IOException e) {
logger.error("Error encountered whilst writing the file. Error : ", e); e.printStackTrace();
}