问题
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