Question

If i want to input file say myfile.txt using cat command

say "cat myfile.txt > java myMain"

What should I write in myMain function ? Is myfile.txt stored directly in args[0] or is there a way to reference it ?

Was it helpful?

Solution

You wouldn't do it quite like that - that's currently redirecting to a file. You either want to pipe it to java, or redirect in the other way:

java Foo < myTextFile

or

cat myTextFile | java Foo

Next, you should use System.in, as you're basically using the contents of that file as standard input instead of the console:

import java.io.*;

public class CopyInput {
    public static void main(String[] args) throws IOException {
        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(System.in, Charset.defaultCharset()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Read: " + line);
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top