Java – How to read a text file in to a scanner using command line in Java

command-linecommand-line-argumentsjava

I have a small snippet of code that will ask user to type input such as

5
12
59
58
28
58

The first number will indicate the size of the array i need to create and the rest of the numbers will be stored in that array. So with the given input an array of size 5 would be created and the numbers following would be stored in the array.

my code

public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         int size = sc.nextInt();
         int[] array = new int[size];

        for(int i =0; i<size; i++)
        {
            array[i] = sc.nextInt();
        }                       
}

I was wondering is there a way of just feeding a text file instead of typing numbers manually. I mean know there are ways to read text files but is there a way to just feed it in command line. I Know in c there is some simple command where you can just type something like that and it works-> ./code.out > input.txt

Best Solution

Assuming that you're using a bash or POSIX command line interface, it's really quite simple.

1) Create a file named "input.txt" where you'll keep your input (in this case, the numbers).

2) Save your input into the file (ie, by copying and pasting the numbers into the file).

3) Assuming that you compiled your java file with javac, run the program like this:

java yourprogram < input.txt

4) And perhaps if you want to save your output to a file:

java yourprogram < input.txt > output.txt

To see more on bash redirection, read the web page corresponding to this link: https://www.gnu.org/software/bash/manual/html_node/Redirections.html.