Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

java - Replace string in file

I'm looking for a way to replace a string in a file without reading the whole file into memory. Normally I would use a Reader and Writer, i.e. something like the following:

public static void replace(String oldstring, String newstring, File in, File out)
    throws IOException {

    BufferedReader reader = new BufferedReader(new FileReader(in));
    PrintWriter writer = new PrintWriter(new FileWriter(out));
    String line = null;
    while ((line = reader.readLine()) != null)
        writer.println(line.replaceAll(oldstring,newstring));

    // I'm aware of the potential for resource leaks here. Proper resource
    // handling has been omitted in the interest of brevity
    reader.close();
    writer.close();
}

However, I want to do the replacement in-place, and don't think I can have a Reader and Writer open on the same file concurrently. Also, I'm using Java 1.4, so dont't have access to NIO, Scanner, etc.

Thanks, Don

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"In place" replacing usually isn't possible for files, unless the replacement is exactly the same length as the original. Otherwise the file would need to either grow, thus shuffling all later bytes "to the right", or shrink. The common way of doing this is reading the file, writing the replacement to a temporary file, then replacing the original file with the temporary.

This also has the advantage that the file in question is at all times either in the original state or in the completely replaced state, never in between.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...