Search code examples
javafilefile-readfile-writing

Java read txt file string by string and write another txt keeping the position of the words


i have a txt file that contain some words and what i want to do is to read this file one word at time (string), manipulate this string, and then write another txt file but keeping the position of the original words. For example, if my input is something like this:

Hello, this is a
test

i want my output to be in 2 line, like the input. With my code i'm getting something like this (like the append):

hello,
this
is
a
test

Here's my code for this part:

Scanner sc2=null;
try{
    sc2 = new Scanner (new File(fileInput));
    }catch(FileNotFoundException fnfe)
    {
    System.out.println("File not found");
    }
while(sc2.hasNextLine())
{
     Scanner s2=new Scanner (sc2.nextLine());
     while(s2.hasNext())
     {
      String word = s2.next();
     //Here i manipulate the string, and the result is stored in the string "a"

      try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileOutput, true))))
                {
                    out.println(a);
                }catch (IOException e){}
      }
}

(fileInput and fileOutput are defined like

String fileInput="path";

I thnk the PrintWriter i am using, is doing just an append to the file, but i tried to replace this PrintWriter with the FileWriter and the OutputStreamWriter but they only wrote the last string (they overwrite each string with the newest, so in the end i got a txt with only the last string in it).

I have to read the input file one word at time because i need to perform some manipulation on it, and then i have to write the output in the same way of the input. If the words are numbers and my operation on them is a simple +1, the input/output would look like this: input:

5, 7, 8,
4, 2

output:

6, 8, 9,
5, 3

and not like the append with each word in a new line.


Solution

  • Write the lines as you read them:

    try(PrintWriter out = new PrintWriter(new BufferedWriter(
                                          new FileWriter(fileOutput)))) {
        while(sc2.hasNextLine()) {
            String line = sc2.nextLine();
            Scanner s2 = new Scanner(line);
            while(s2.hasNext()) {
                // use the words in line
            }
            // write the line
            out.println(line);
        }
    }