首页 > 解决方案 > how to edit file contents(numbers) by java?

问题描述

i want to edit the text file contents while i'm adding contents of students

              *scoreboard*
 students :4 people
 blah blah

to

              *scoreboard*
 students :21 people
 blah blah

regardless of number of the people

ex)

students :9 people ->  students :13 people
students :4 people ->  students :21 people

this code is adding contents. (contents of blah blah) and additionally i want to edit count of students (increased count of students) the important thing is to sense number of the student. i have no clue about it

String addmessage ="";
for(a=0;a<haksu;a++)    
{
    addmessage +="" + String.format("%10s",ab[a].hakb) + String.format("%10s",ab[a].n) + String.format("%12d",ab[a].g) + String.format("%12d",ab[a].s) + String.format("%12d",ab[a].y) + String.format("%12d",ab[a].sa)+ String.format("%12d",ab[a].sc) + String.format("%12d",ab[a].c) + String.format("%12.1f",ab[a].p) +"      "+ ab[a].h + "\n";

}
try {
    BufferedWriter bwrite = new BufferedWriter(new FileWriter(file,true));
    bwrite.write(addmessage + "\n");
    bwrite.close();
}
finally {

}
filereader = new FileReader(file);
bufReader = new BufferedReader(filereader);
line = "";
while((line = bufReader.readLine()) != null){
    System.out.println(line);
}
bufReader.close();

标签: java

解决方案


就地修改文件相当困难,尤其是在某些字段的大小发生变化时。鉴于您的文件似乎不会太长,一个更简单的解决方案是将文件完全读入内存,然后在原始文件上写出修改后的内容。


推荐阅读