0

basically i am writing a program that requires the functionality of being able to either replace a specific line of text by looping through every line and comparing or being able to take a line number and then replacing it with new text preferably the second solution. so say i have a text file

the
sky
is
blue

and i want to replace the word sky with ocean. either i can say loop through and find words of the value sky or i can specify that the line i want to replace is on line 2 and then replace it like that. either way the solution should be

the
ocean
is
blue

I have no clue how to do this any help is appreciated.

Mo0nbase
  • 123
  • 10

2 Answers2

0

Create and open a stream to the file. Then, in a loop read line by line and write to a new file which you created using another stream, when your loop counter variable equals the line number you want, then write the new line instead of that one, let the loop finish. Finally, close both streams. Remember that the first line is not 1 but rather 0. Remember that you must loop until reaching the end of file, you must maintain a loop variable independently, this means you can't use a for loop, but rather a while loop.

Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21
0

Read the file and replace the word you want

     public static void main(String[] args) throws IOException {
        File file = new File("file.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));

        String words = "", list = "";

        while ((words = reader.readLine()) != null) {
            list += words + "\r\n";
        }
        reader.close();

        String replacedtext = list.replaceAll("sky", "" + "ocean");

        FileWriter writer = new FileWriter("file.txt");
        writer.write(replacedtext);
        writer.close();

    }
}
Jason
  • 72
  • 6