简体   繁体   中英

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

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.

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); 
        }    
    }
}  

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM