41

我不确定您应该如何从 Java 文件的系统输入中读取数据。

我希望能够打电话java myProg < file

其中 file 是我想要作为字符串读取并在 main 方法中提供给 myProg 的内容。

有什么建议么?

4

8 回答 8

66

您可以使用System.in从标准输入中读取。它的工作原理就像从键盘输入一样。操作系统处理从文件到标准输入的处理。

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());
    }
}
于 2011-03-30T15:01:58.997 回答
19

好吧,您可以阅读System.in它本身,因为它是一个有效的InputStream. 或者,您也可以将其包装在BufferedReader

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
于 2011-03-30T15:03:39.433 回答
7

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

于 2014-10-09T13:47:07.923 回答
5

使用 System.in,它是一个 InputStream,正好服务于这个目的

于 2011-03-30T15:01:29.867 回答
4

您可以像使用键盘输入一样读取System.in,例如InputStreamReaderScanner

于 2011-03-30T15:05:04.160 回答
1

您可以致电java myProg arg1 arg2 ...

public static void main (String args[]) {
    BufferedReader in = new BufferedReader(new FileReader(args[0]));
}
于 2011-03-30T15:05:42.263 回答
-3

You probably looking for something like this.

FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
于 2014-06-22T17:35:10.433 回答
-6
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");
}
}
于 2013-07-16T04:12:31.267 回答