如对类似问题的公认答案中所建议:
同时以写入模式打开一个临时文件,对于每一行,读取它,必要时进行修改,然后写入该临时文件。最后,删除原始文件并重命名临时文件。
根据您的实现,类似于以下内容:
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class ReplaceFileContents { public static void main(String[] args) { new ReplaceFileContents().replace(); } public void replace() { String oldFileName = "try.dat"; String tmpFileName = "tmp_try.dat"; BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(oldFileName)); bw = new BufferedWriter(new FileWriter(tmpFileName)); String line; while ((line = br.readLine()) != null) { if (line.contains("1313131")) line = line.replace("1313131", ""+System.currentTimeMillis()); bw.write(line+"n"); } } catch (Exception e) { return; } finally { try { if(br != null) br.close(); } catch (IOException e) { // } try { if(bw != null) bw.close(); } catch (IOException e) { // } } // once everything is complete, delete old file.. File oldFile = new File(oldFileName); oldFile.delete(); // And rename tmp file's name to old file name File newFile = new File(tmpFileName); newFile.renameTo(oldFile); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)