Handling Java command line arguments in the format “cat file.txt | java YourMainClass”

醉酒当歌 提交于 2019-12-08 11:30:00

问题


I've never used java from the terminal before, and I certainly have never coded for it. My question is simple: How do I intake a file when the calling format is

cat  file.txt  |  java  YourMainClass

I have the rest of the code up and running swimmingly, I just need to take the given file name into my main method.


回答1:


Since the cat command displays the contents of the file, you need to use the System.in buffer to capture the data coming in from that command. You can use a BufferedReader pointing to System.in to loop through the data and process it.

Look at this 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); 
        }    
    }
}  



回答2:


As you are looking to read from System.in as the output from cat, you could do:

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

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


来源:https://stackoverflow.com/questions/12999357/handling-java-command-line-arguments-in-the-format-cat-file-txt-java-yourmain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!