Reading in from System.in - Java [duplicate]

2019-01-02 23:22发布

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?

8条回答
放荡不羁爱自由
2楼-- · 2019-01-03 00:22

In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

After this statement executes, br is a character-based stream that is linked to the console through System.in.

This is taken from the book Java- The Complete Reference by Herbert Schildt

查看更多
唯我独甜
3楼-- · 2019-01-03 00:24

Use System.in, it is an InputStream which just serves this purpose

查看更多
登录 后发表回答