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条回答
smile是对你的礼貌
2楼-- · 2019-01-03 00:08

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));
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-03 00:10

You would read from System.in just like you would for keyboard input using, for example, InputStreamReader or Scanner.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 00:11
class myFileReaderThatStarts with arguments
{

 class MissingArgumentException extends Exception{      
      MissingArgumentException(String s)
  {
     super(s);
  }

   }    
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value 
if(args.length>0)
{
    // do something with args[0]
}
else
{
// default in a path 
// or 
   throw new MissingArgumentException("You need to start this program with a path");
}
}
查看更多
疯言疯语
5楼-- · 2019-01-03 00:15

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.

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());
    }
}
查看更多
仙女界的扛把子
6楼-- · 2019-01-03 00:17

You can call java myProg arg1 arg2 ... :

public static void main (String args[]) {
    BufferedReader in = new BufferedReader(new FileReader(args[0]));
}
查看更多
三岁会撩人
7楼-- · 2019-01-03 00:21

You probably looking for something like this.

FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
查看更多
登录 后发表回答