0

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

    }

1 Answers1

1

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();
       }   
      }  
    }
Selva
  • 1,620
  • 3
  • 33
  • 63
  • Thanks for the information. It's quite helpful. However is there a way of avoid using the FileInputStream? I suppose with the input stream it can only accept files as input but not input from the keyboard? – stillAFanOfTheSimpsons Sep 25 '14 at 05:29
  • see my answer to read a file name from keyboard.It's works as you expected – Selva Sep 25 '14 at 05:35