Use java to modify file contents in place

后端 未结 3 530
北海茫月
北海茫月 2020-12-21 02:22

I need to modify specific contents of a file in-place.
I do not want to create a new file and rewrite the old. Also the files are small

3条回答
  •  长情又很酷
    2020-12-21 03:11

    Assuming you want to be able to manipulate the file content as text, and assuming that the file fits in memory (which you say is a valid assumption), then perhaps you might find the methods in Commons IO FileUtils useful:

    http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html

    For example:

    File f = new File("my-file.txt");
    List lines = FileUtils.readLines(f, "UTF-8");
    List outLines = modify(lines); // Do some line-by-line text processing
    FileUtils.writeLines(f, "UTF-8", outLines);
    

    So, you're reading the file content into memory, modifying it in-memory, and then over-writing the original file with the new content from memory. Does that meet your criteria for "in-place"?

提交回复
热议问题