Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in from System.in - Java [duplicate]

I am not sure how you are supposed to read in from system input from a Java file.

I want to be able to call java myProg < file

Where file is what I want to be read in as a string and given to myProg in the main method.

Any suggestions?

like image 735
Alex Avatar asked Mar 30 '11 14:03

Alex


2 Answers

You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.

import java.util.Scanner; class MyProg {     public static void main(String[] args) {         Scanner sc = new Scanner(System.in);         System.out.println("Printing the file passed in:");         while(sc.hasNextLine()) System.out.println(sc.nextLine());     } } 
like image 130
corsiKa Avatar answered Sep 24 '22 07:09

corsiKa


Well, you may read System.in itself as it is a valid InputStream. Or also you can wrap it in a BufferedReader:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
like image 26
xappymah Avatar answered Sep 24 '22 07:09

xappymah