简体   繁体   中英

Cannot get PrintWriter to replace text in file

I am trying to complete a simple program that uses the command line to replace a specified String in a file. Command line entry would be java ReplaceText textToReplace filename The code completes, but the file does not replace the specified string. I have Googled similar situations but I cannot figure out why my code is not working.

 import java.io.*;
import java.util.*;

public class ReplaceText{
    public static void main(String[] args)throws IOException{
    if(args.length != 2){
        System.out.println("Incorrect format. Use java ClassName textToReplace filename");
        System.exit(1);
    }

    File source = new File(args[1]);
    if(!source.exists()){
        System.out.println("Source file " + args[1] + " does not exist.");
        System.exit(2);
    }


    File temp = new File("temp.txt");
    try(
        Scanner input = new Scanner(source);
        PrintWriter output = new PrintWriter(temp);

        ){
            while(input.hasNext()){
                String s1 = input.nextLine();
                String s2 = s1.replace(args[0], "a");
                output.println(s2);

            }
            temp.renameTo(source);
            source.delete();

        }

    }
}

Edit: edited the code so I am not reading and writing to the file at the same time, but it still does not work.

You can't replace strings a file in general. You need to read the input line by line, replace each line as necessary, and write each line to a new file. Then delete the old file and rename the new one.

First of all you have a problem with your logic. You are renaming your temporary file then immediately deleting it. Delete the old one first, then rename the temporary file.

Another problem is that you are attempting to do perform the delete and rename within your try block:

try(
    Scanner input = new Scanner(source);
    PrintWriter output = new PrintWriter(temp);
){
    ...
    temp.renameTo(source);
    source.delete();
}

Your streams are not automatically closed until the try block ends. You will not be able to rename or delete while the stream is open. Both delete and renameTo return a boolean to indicate whether they were successful so it may be prudent to check those values.

Correct code may look something like:

try(
    Scanner input = new Scanner(source);
    PrintWriter output = new PrintWriter(temp);
){
    while(...)
    {
       ...
    }
}
// Try block finished, resources now auto-closed
if (!source.delete())
{
    throw new RuntimeException("Couldn't delete file!");
}
if (!temp.renameTo(source))
{
    throw new RuntimeException("Couldn't rename file!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM