[英]How to stop overwrite txt file and let it write in new line
问题出现在我的代码中,它首先接受用户输入并将其放入文本文件并询问是否要再次回答它但是每个用户都这样做并结束循环它只需要最新的用户输入并且只是覆盖以前的输入用户做了。 但这不是我想要的代码。 相反,新答案应该在文本文件的新行上。
public static void main(String[] args) throws IOException {
// TODO code application logic here
int saldo = 10000;
String anw = "j";
int cost;
try{
File folder = new File("folderName");
folder.mkdir();
File f = new File(folder, "file1.txt"); //file to folder
f.createNewFile(); //skapar fil
//Scanner fileIn = new Scanner(f);
System.out.println("File path" +f.getPath());
//.----------------------------------
while(anw.equals("j")){
Scanner in = new Scanner(System.in);
FileWriter fWriter ;// removed null
BufferedWriter writr;// removed null
System.out.println("Ange utgiftspost:"); //post
String post = in.nextLine();
System.out.println("Ange kostnad:"); //kost
cost=in.nextInt();
in.nextLine();
saldo = +saldo -cost;
System.out.println("saldo:" +saldo);
System.out.println("Vill du mata in fler uppgifter? (j/n) :");
anw = in.nextLine();
String fileContent = "---"+post+"---"+cost+"---"+saldo;
fWriter = new FileWriter(f);
writr = new BufferedWriter(fWriter);
writr.write(fileContent);
writr.newLine();
if (anw.equals("n")) {
writr.close();
//writer.close();
//System.out.println("---"+post+"---"+cost+"---"+saldo);
}
} //frågan slut
}//try
//Scanner fileIn = new Scanner(f);
catch(Exception e){
System.err.println(e.getMessage());
}
}
您正在为每个循环定义新的Scanner
和*Writer
对象,这些对象会导致内容被覆盖。 定义一次并重复使用每次迭代。
Scanner in = new Scanner(System.in);
FileWriter fWriter = new FileWriter(f);
BufferedWriter writr = new BufferedWriter(fWriter);
while (anw.equals("j")) {
// ...
}
不要忘记在循环后关闭资源。
在我之前的问题中 ,我有@ASKW回答这个问题。 他评论说BufferedWriter
对于我的特定情况是行不通的。 但是单独使用FilterWriter
和append
可以解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.