【问题标题】:Handling Java command line arguments in the format “cat file.txt | java YourMainClass”以“cat file.txt | ”格式处理 Java 命令行参数java YourMainClass”
【发布时间】:2012-10-21 15:43:29
【问题描述】:

我以前从未在终端中使用过 java,当然我也从未为它编写过代码。我的问题很简单:当调用格式为

cat  file.txt  |  java  YourMainClass

我已经准备好其余的代码并顺利运行,我只需要将给定的文件名放入我的 main 方法中。

【问题讨论】:

  • 以下答案忘记明确说明的内容:您没有得到文件名,只是输入。你上面的例子相当于java YourMainClass <file.txt

标签: java terminal


【解决方案1】:

由于 cat 命令显示文件的内容,因此您需要使用 System.in 缓冲区来捕获从该命令传入的数据。您可以使用指向 System.in 的 BufferedReader 来遍历数据并对其进行处理。

看看这个Example

public class ReadInput {
    public static void main(String[] args) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String x = null;  
        while( (x = input.readLine()) != null ) {    
            System.out.println(x); 
        }    
    }
}  

【讨论】:

  • 我不认为有任何方法可以从 windows 进行调用吗?
  • 您可以制作一个 .bat 文件并让它在命令行中执行对您程序的 java 调用。或者将其制作成一个显示在 JFrame 中的摇摆应用程序。 bat 文件将只包含您在命令行中键入的命令。我想最好的解决方案会根据你在这里的需要而改变。
【解决方案2】:

当您希望从 System.in 读取作为 cat 的输出时,您可以这样做:

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

String line;
while ((line = br.readLine()) != null) {
   // use line...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2012-11-24
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多