我希望你能帮我这个,我正在读一个有多行的文件。我使用BufferedReader来分离数据。如果数据1与新数据1输入不匹配,它将使用BufferedWriter将新数据1输入替换为旧数据1.使用以下代码,它确实更改了数据1,但它附加了其他行数据2和3。我想只更改数据1,但线条保持不变。
Example(Input)
abc, 123, 456, 3345
test, t245, 442, d444
dddd, 4444, ffff, 333
public void test(String DATA1, String DATA2) throws IOException{
br = new BufferedReader(new FileReader(file));
while ((CurrentLine = br.readLine()) != null) {
String[] modify = CurrentLine.split(split);
String data1 = modify[0];
String data2 = modify[1];
String data3 = modify[2];
String data4 = modify[3];
bw = new BufferedWriter(new FileWriter(file, true));
if (!data1.contains(DATA1)) {
StringBuilder sb = new StringBuilder();
while(CurrentLine != null){
sb.append(CurrentLine.replace(data1, DATA1));
sb.append("\n");
CurrentLine = br.readLine();
}
bw.write(sb.toString());
RESIDENTS_OLDDETAILS = new File(oldfile);
RESIDENTS_OLDDETAILS.delete();
RESIDENTS_NEWDETAILS = new File(newfile);
RESIDENTS_NEWDETAILS.renameTo(old);
br.close();
bw.close();
Example(Output of the above code)
newabc, t245, 442, d444
newabc, t245, 442, d444
newabc, t245, 442, d444
Expected output
aaa, 123, 456, 3345
test, t245, 442, d444
dddd, 4444, ffff, 333
Edited Expected output
aaa, 123, 456, 3345
test, t245, 442, d444
dddd, 4444, ffff, 333aaa, 123, 456, 3345
test, t245, 442, d444
dddd, 4444, ffff, 333
答案 0 :(得分:0)
看一下这些修改,您可能希望在检测到不同之后立即替换data1,然后只需阅读其余行并将其附加到StringBuilder
public static void main(String[] args) throws Exception {
test("aaa", "bbb");
}
public static void test(String DATA1, String DATA2) throws IOException {
String file = "data.txt";
String newFile = "dataNew.txt";
String CurrentLine = "";
BufferedReader br = new BufferedReader(new FileReader(file));
while ((CurrentLine = br.readLine()) != null) {
String[] modify = CurrentLine.split(", ");
String data1 = modify[0];
String data2 = modify[1];
String data3 = modify[2];
String data4 = modify[3];
BufferedWriter bw = new BufferedWriter(new FileWriter(newFile, true));
if (!data1.contains(DATA1)) {
StringBuilder sb = new StringBuilder();
sb.append(CurrentLine.replace(data1, DATA1));
sb.append("\n");
while ((CurrentLine = br.readLine()) != null) {
sb.append(CurrentLine);
sb.append("\n");
}
bw.write(sb.toString());
File RESIDENTS_OLDDETAILS = new File(file);
RESIDENTS_OLDDETAILS.delete();
File RESIDENTS_NEWDETAILS = new File(newFile);
RESIDENTS_NEWDETAILS.renameTo(RESIDENTS_OLDDETAILS);
br.close();
bw.close();
break;
}
}
}
输入:
abc,123,456,3345
test,t245,442,d444
dddd,4444,ffff,333
输出:
aaa,123,456,3345
test,t245,442,d444
dddd,4444,ffff,333