java如何修改一个文件的内容呢?
下文笔者讲述使用java代码修改文件内容的方法分享,如下所示:
实现思路: 1.使用两个Buffer,一个作为读Buffer,一个作为写Buffer 2.将读Buffer中的内容,经过变更后放入到写Buffer中 3.对写buffer产生的文件,进行变更名称后,作为修改后的文件输出例:
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 = "source.txt"; String tmpFileName = "tmp_source.txt"; 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("java265.com")) line = line.replace("java265.com", ""+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); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。