Search code examples
javafileiojava.util.scannerprintwriter

Java IO: Using scanner and printWriter to copy the contents of a text file and put them in another text file


Alright so I have a very small program I'm working on designed to take the contents of a text file, test.txt, and put them in another empty file testCopied.txt . The trick is that I want to use Scanner and printWriter as I am trying to understand these a bit better.

Here is what my code looks like:

import java.io.*;
import java.util.*;

public class CopyA
{
   public static void main(String [] args)
   {
      String Input_filename = args[0];
      String Output_filename = args[1];
      char r = args[2].charAt(0);

      try
      {
         Scanner sc = new Scanner(new File(Input_filename));
         FileWriter fw = new FileWriter(Output_filename);
         PrintWriter printer = new PrintWriter(fw);

         while(sc.hasNextLine())
         {
            String s = sc.nextLine();
            printer.write(s);
         }
         sc.close();               
      }
      catch(IOException ioe)
      {
         System.out.println(ioe);
      }
   }
}

This compiles, but when I look at testCopied.txt it is still blank, and hasn't had test.txt's content transferred to it. What am I doing wrong? Java IO is pretty confusing to me, so I'm trying to get a better grasp on it. Any help is really appreciated!


Solution

  • You have missed out flush() and close() for the PrintWriter object which you need to add

    and then use the line separator using System.getProperty("line.separator") while writing each line into second file.

    You can refer the below code:

    PrintWriter printer = null;
    Scanner sc = null;
    try
      {
         String lineSeparator = System.getProperty("line.separator");
    
         sc = new Scanner(new File(Input_filename));
         FileWriter fw = new FileWriter(Output_filename);
         printer = new PrintWriter(fw);
    
         while(sc.hasNextLine())
         {
            String s = sc.nextLine()+lineSeparator; //Add line separator
            printer.write(s);
         }
      }
      catch(IOException ioe)
      {
         System.out.println(ioe);
      } finally {
        if(sc != null) {
           sc.close();  
        }
        if(printer != null) {
          printer.flush();
          printer.close();
         }
     }
    

    Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).