我想替换第二行文件的内容,能不能有人帮我根据下面的文件格式和监听方法。
1324254875443
1313131
Paid
0.0
第二行很长,希望替换为currentTimeMillis()
。
/************** Pay Button Listener **************/
public class payListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
try {
FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line.replace(System.currentTimeMillis();
lines.add(line);
bw.write(line);
} //end if
} //end try
catch (Exception e) {
} //end catch
} //end while
}//end method
发布于 2016-03-17 17:45:02
尽管这个问题由来已久,但我想补充的是,自从Java1.7使用java.nio.file.Files
以来,实现这个问题要容易得多
List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
if (line.contains("1313131")) {
newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
} else {
newLines.add(line);
}
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
发布于 2011-12-19 23:20:17
我可以建议使用Apache Commons IO库。在那里,您将找到类org.apache.commons.io.FileUtils。您可以使用它:
File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);
这段代码将整个文件内容读取到List of String
中,并更改第二行的内容,然后将列表写回文件。
发布于 2011-12-19 23:20:44
我不确定同时读写同一个文件是不是一个好主意。我认为将文件逐行读取到String
数组中,替换第二行,然后将String
数组写回文件中会更好。
https://stackoverflow.com/questions/8563294
复制相似问题