Search code examples
javatext-filesread-write

Modify contents of text file and write to new file in java


So I've got the basic code for this however due to the while loop I'm using, I can really only write the last line of the text file to the new file. I'm trying to modify the text from testfile.txt and write it to a new file named mdemarco.txt. The modification I'm trying to do is add a line number in front of each line. Does anybody know a way to maybe write the contents of the while loop to a string while it runs and output the resulting string to mdemarco.txt or anything like that?

public class Writefile
{
public static void main(String[] args) throws IOException
{
  try
  {
     Scanner file = new Scanner(new File("testfile.txt"));
     File output = new File("mdemarco.txt");
     String s = "";
     String b = "";
     int n = 0;
     while(file.hasNext())
     {
        s = file.nextLine();
        n++;
        System.out.println(n+". "+s);
        b = (n+". "+s);
     }//end while
     PrintWriter printer = new PrintWriter(output);
     printer.println(b);
     printer.close();
  }//end try
     catch(FileNotFoundException fnfe)
  {
     System.out.println("Was not able to locate testfile.txt.");
  }
}//end main
}//end class

The input file text is:

do
re
me
fa 
so
la
te
do

And the output I'm getting is only

8. do

Can anybody help?


Solution

  • The String variable b is overwriten in each iteration of the loop. You want to append to it instead of overwriting (you may also want to add a newline character at the end):

    b += (n + ". " + s + System.getProperty("line.separator"));
    

    Better yet, use a StringBuilder to append the output:

    StringBuilder b = new StringBuilder();
    int n = 0;
    while (file.hasNext()) {
        s = file.nextLine();
        n++;
        System.out.println(n + ". " + s);
        b.append(n).append(". ").append(s).append(System.getProperty("line.separator"));
    }// end while
    PrintWriter printer = new PrintWriter(output);
    printer.println(b.toString());