[英]How to overwrite a text file in java?
我正在向GUI读取一个名为charList.txt的文本文件,然后通过该GUI进行了一些更改。 我希望将所有更改保存到相同的文本文件中,但我不知道如何。 因此,我创建了一个名为new.text的新文本文件,并将其重命名以覆盖我的charList.text。 但是失败了。 有人可以给我一些建议吗? 谢谢!
try {
FileWriter edit = new FileWriter("new.txt");
PrintWriter pedit = new PrintWriter(edit);
FileReader fr = null;
String line = "null";
try{
fr = new FileReader("charList.txt");
}
catch (FileNotFoundException e1){
e1.printStackTrace();
}
BufferedReader bf = new BufferedReader(fr);
while(line != null){
try{
line = bf.readLine();
}
catch (IOException e1){
e1.printStackTrace();
}
if (line != null){
fields = line.split("\t");
if (Integer.parseInt(idField.getText()) != Integer.parseInt(fields[0])){
pedit.println(line);
}
else{
pedit.println(Integer.parseInt(idField.getText()) + "\t" + moneyBefore + "\t" + userName + "\t" + fields[3] + "\t" + fields[4] + "\t"
+ fields[5] + "\t" + moneyAfter);
}
}
}
pedit.close();
bf.close();
File old = new File("charList.txt");
old.delete();
File oldfile =new File("new.txt");
File newfile =new File("charList.txt");
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
关闭两个流。 重命名之前删除oldFile。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.