Replace a String within a Text File

Asked 2 years ago, Updated 2 years ago, 82 views

We are now solving the problem of replacing a string in a text file by taking it over the command line, and the first and last searched string should be output as a specific string other than the one you want to replace. I don't know the process of changing the last searched string here. `

public static void main(String[] args)throws Exception{
    int count=0;
    if(args.length!=3){
        System.out.println("Usage: java ReplaceText targetFile oldStr newStr");
        System.exit(1);
    }
    File SourceFile = new File("in.txt");
    if(!SourceFile.exists()){
        System.out.println("SourceFile does not exist");
        System.exit(2);
    }
    File targetFile = new File(args[0]);
    try(Scanner input = new Scanner(SourceFile);
        PrintWriter output = new PrintWriter(targetFile);
        ){
        String arr[];
        String same[];
        while(input.hasNext()){
            String s1 = input.nextLine();
            String s2 = s1.replaceAll(args[1], "%%%");
            output.println(s2);
            count++;
            if(s1.equals(args[1])){
                break;
            }
        }
        while(input.hasNext()){
            String s1 = input.nextLine();
            String s2 = s1.replaceAll(args[1], args[2]);
            output.println(s2);
            if(s1.equals(args[1])){
                count++;    
            }
        }
    }
    System.out.println(args[1]+" : "+count);
}

I'm also attaching the code I've prepared.

java file-io

2022-09-22 14:00

1 Answers

It's hard to process it on a line basis. Take care of the whole file

Save the contents of the file to the String variable

-> import java.nio.charset.*;
-> import java.nio.file.*;
-> String contents = new String (Files.readAllBytes (Paths.get(".profile")); Charset.defaultCharset()); // contents is the full file content

Create a new file and write changes

-> import java.nio.file.*;
-> Files.write(Files.createFile(Paths.get("mytest.txt")), contents.replaceFirst("HOME", "HOUSE").getBytes())

By the way, there is replaceFirst in String, but there is no replaceLast.

I have to make it and use it.

There is no replaceLast, but there is lastIndexOf, so you can know the location of the last word.

The contents is the body you want to search for

Search Word is a search word

Replacement is a word to convert.

public static String replaceLast(String contents, String searchWord, String replacement) {
    int regexIndexOf = contents.lastIndexOf(searchWord);
    If (regexIndexOf== -1){ // Return string if no search word exists
        return contents;
    }else{
        return contents.substring(0, regexIndexOf) + replacement + contents.substring(regexIndexOf + searchWord.length());
    }
}

I think I can handle the assignment when I'm ready for this.


2022-09-22 14:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.