Search code examples
javafileprintingiosystem.in

java use sanner for i/o and file redirection


I am trying to read input (from keyboard and also with command line file redirection), process the input info. and output it to a file. My understanding is that using the following code, and use command line: java programName< input.txt >output.txtwe should be able to print the output to a file. But it doesn't work. Can someone please help to point out the correct way of doing this? Many thanks!

public static void main(String[] args) {

    Scanner sc = new Scanner (System.in);

    int [] array= new int[100];
    while (sc.hasNextLine()){
        String line = sc.nextLine();

        .....//do something

    }

Solution

  • Try the below code

    import java.io.*;
    import java.util.*;
    /**
     *
     * @author Selva
     */
    public class Readfile {
      public static void main(String[] args) throws FileNotFoundException, IOException{
       if (args.length==0)
       {
         System.out.println("Error: Bad command or filename.");
         System.exit(0);
       }else {
           InputStream in = new FileInputStream(new File(args[0]));
           OutputStream out = new FileOutputStream(new File(args[1]));
          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0) {
             out.write(buf, 0, len);
          }
          in.close();
          out.close();
       }   
      }  
    }
    

    Run this code using If your text file and java code is same folder run the program like below.

    java Readfile input.txt output.txt

    If your text file and java code is different folder run the program like below.

    java Readfile c:\input.txt c:\output.txt
    

    If you read input form keyboard using scanner.Try the below code

    import java.io.*;
    import java.util.*;
        /**
         *
         * @author Selva
         */
        public class Readfile {
          public static void main(String[] args) throws FileNotFoundException, IOException{
           Scanner s=new Scanner(System.in);
           if (args.length==0)
           {
             System.out.println("Error: Bad command or filename.");
             System.exit(0);
           }else {
               System.out.println("Enter Input FileName");
               String a=s.nextLine();
               System.out.println("Enter Output FileName");
               String b=s.nextLine();
               InputStream in = new FileInputStream(new File(a));
               OutputStream out = new FileOutputStream(new File(b));
              byte[] buf = new byte[1024];
              int len;
              while ((len = in.read(buf)) > 0) {
                 out.write(buf, 0, len);
              }
              in.close();
              out.close();
           }   
          }  
        }