[英]edit a line in text file
所以我有一个文本文件,包括:
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
)将消失/删除。 我希望一切都是一样的,除非not voting
给定/输入的数字没有投票。
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"...;
outfile.println(all);
outfile.flush();
} else {
outfile.println( line );
}
如果没有匹配则复制到输出。
我应该补充说,使用正则表达式进行单个字符串比较应该简化为更简单的info[1].equals(numberforvote)
。 但是调用numberforvote = numberforvote.trim();
可能有用。
您的输出文件被完全覆盖,因此您必须编写所有行,即使是那些您不打算修改的行:
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();
将它移到if
之外,只更改你需要更改的部分。 这样你可以改变你想要的任何东西然后重建线。
if(info[1].matches(numberforvote)){
into[0] = VOTED;
}
all=info[0]+"/"+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();
或清理那条丑陋的线条
StringBuilder sb = new StringBuilder();
for (String element : info){
sb.append(element);
}
outfile.println(sb.toString());
其他答案
您可以像其他人建议的那样输出未更改的行
outfile.println(line);
但如果您想稍后进行其他更改,则不具备灵活性。
您应该简化拆分并写入:
String [] info=line.split("/",2);
if ( info.length == 2 ) {
...
outfile.println("VOTED/"+info[1]);
} else {
// input error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.