我有以下代码:
String mID = jTextField1.getText();
String mType = jComboBox1.getSelectedItem().toString();
String mFName = jTextField2.getText();
String mLName = jTextField3.getText();
String mHomePhone = jTextField4.getText();
String mMobilePhone = mPhone2.getText();
String mEmail = jTextField6.getText();
String mHomeAddress = jTextField7.getText();
//Defines the new line of data
String newLine = (mID + " | " + mType + " | " + mFName + " | " + mLName + " | "
+ mHomePhone + " | " + mMobilePhone + " | " + mEmail + " | " + mHomeAddress);
try {
File inFile = new File("Members2.txt");
BufferedReader br;
FileReader reader;
try (PrintWriter writer = new PrintWriter(new BufferedWriter( new FileWriter("Member2_Temp.txt", true)))) {
br = new BufferedReader(new FileReader(inFile));
reader = new FileReader("Members2.txt");
String line;
while (null != (line = br.readLine())) {
if (newLine.equals(line)) {
newLine = line.replace(line, newLine);
}
// Always write the line, whether you changed it or not.
writer.println(newLine);
}
br.close();
reader.close();
writer.close();
}
File tempFile = new File("Member2_Temp.txt");
Path source = tempFile.toPath();
Path newdir = inFile.toPath();
Files.move(source, newdir, REPLACE_EXISTING);
dispose();
new Edit_Member_Final().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Edit_Member_Final.class.getName()).log(Level.SEVERE, null, ex);
}
问题在于它只将已编辑的行打印到文件中,而不打印其余未编辑的行。
如果我有4条记录,程序会因某种原因打印编辑行4次。我该如何解决这个问题?
答案 0 :(得分:2)
修改强>
BufferedReader br;
try (PrintWriter writer = new PrintWriter(new BufferedWriter( new FileWriter("Member2_Temp.txt", true)))) {
br = new BufferedReader(new FileReader(inFile));
String line;
while (null != (line = br.readLine())) {
if (newLine.equals(line)) {
line = line.replace(line, newLine);
}
// Always write the line, whether you changed it or not.
writer.println(line);
}
br.close();
writer.flush();
writer.close();
您正在编写newLine
,只有在找到匹配项时才会有数据
writer.println(newLine);
您也应该像这样写line
,添加else
条件
if (newLine.equals(line)) {
line= line.replace(line, newLine);
}
writer.println(line);