0

I'm doing an assignment where I'm supposed to work with a file. The tester uses the command argument

"java puzzle < sample_input_1.txt"

to run the file with my program. My program being "puzzle" and the file being "sample_input_1.txt".

I've been searching a bit, but i'm not quite sure how to retrieve the data from this file. I'm used to getting the filepath as an argument to main, which I use a scanner to read.

How do I access this file when programming and retrieving it's data? I would like to do something like what a scanner does to read it.

Thanks guys!

1
  • 2
    Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted. If you would like to disassociate this post from your account, see What is the proper route for a disassociation request? Commented Sep 25, 2017 at 10:00

3 Answers 3

1

It's on your standard input stream. To clarify, if you're used to using Scanner's constructor that accepts a File (like this):

Scanner scanner = new Scanner(new File(args[0]));

then use the Scanner's constructor that accepts an InputStream, and pass System.in:

Scanner scanner = new Scanner(System.in);

You should be able to use the scanner in the same manner you're accustomed to after that.

Sign up to request clarification or add additional context in comments.

Comments

0

It comes to you in the stdin stream ( System.in ). The < sample_input_1.txt at the end of the command redirects the stdin stream to the given file. It's present in almost every terminal program. More information can be found here.

Comments

0

In my opinion, the easiest way you can do is using InputStream:

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

    String word;
    do {
    word = br.readLine();
    if (word != null) {
        list.add(word); //if you want add the file content to an ArrayList
    } else {
        return; //case file is empty, program is finished
    }
    } while (word != null);

} catch (Exception e) {
    System.err.println("Error:" + e.getMessage());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.