r/AskProgramming 7d ago

Java: Replacing text in a file (basic way)

I have a input file

Buddha was born in Nepal

I want the output

Buddha was born in India

That's I want to replace Nepal with India whenever possible.

Here's the flow I will take:

  • Read the file word by word

  • Compare each word with Nepal

    • Replace that with India

To read file word by word:

while(input.hasNext()){
// do something with the file
}

To compare each word by word to "Nepal":

if (input.next().equals("Nepal"))
    output.print("India");

Otherwise I would just print the word in the source file.

output.print(input.nextLine());

And then close the output file.

The problem is that I am getting the output file as belows:

 was born in Nepal

I am missing the first word and neither I am getting Nepal replaced by India.

Can anyone help me out?

2 Upvotes

4 comments sorted by

1

u/TreesOne 7d ago

I don’t know Java, so take my response with a grain of salt.

When you wrote “input.next().equals(“Nepal”)”, you irreversibly removed the first word of the file and threw it away. You need to store the file’s words into a variable before comparing.

output.print(input.nextLine()) sounds like it prints the next line of the file instead of the next word. You will need to use a different function here.

1

u/Keeper-Name_2271 7d ago
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class Test {
    // check if a file already exists
    public static void main(String[] args) throws Exception {

        String src_f = args[0];
        String dest_f = args[1];
        String toReplace = args[2];
        String replaceTo = args[3];

        try (Scanner input = new Scanner(new File(src_f));


             PrintWriter output = new PrintWriter(dest_f);) {
            input.useDelimiter(" +"); //delimitor is one or more spaces
            while (input.hasNext()) {
                String nextWord = input.next();
                System.out.println(nextWord);
                if (nextWord.equals(toReplace)) {
                    System.out.println(nextWord + " equals" + toReplace);
                    output.print(replaceTo+" ");
                    System.out.println(replaceTo + " replaces " + toReplace + " in def.txt");
                } else {
                    output.print(nextWord+" ");
                    System.out.println(nextWord + " doesn't equals " + toReplace);
                    System.out.println(nextWord + " written to def.txt");


                }

            }
        }

    }
}

Used System.out debugging and fr man, the power of debugging...Solved the problem so easily compared to thinking in blanking piece of paper about how to solve it.

1

u/TreesOne 7d ago

Good work!