所以我有一个包含以下内容的文本文件:
not voting/1/harold/18
not voting/2/isabel/24
这描述了not voting/number for vote/name/age
。我的目标是将 not voting
编辑为 voted
但仍保留其他信息(number for vote/name/age
)。用户将输入要投票的号码,如果存在,not voting
将自动更改为 voted
这是我的代码:
File original = new File("C:\\voters.txt");
File temporary = new File("C:\\tempvoters.txt");
BufferedReader infile = new BufferedReader(new FileReader(original));
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));
numberforvote=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();
temporary.renameTo(original);
这有效,但我的代码的问题是第二行 (not voting/2/isabel/24
) 将消失/删除。除了给定/输入的投票号码中的不投票
,我希望一切都一样。
最佳答案
你的输出文件被完全覆盖,所以你必须写下所有行,甚至那些你不打算修改的行:
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
}
else{
outfile.println(line); // this will write the "unchanged" lines
}
outfile.flush();
关于java - 编辑文本文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35993121/