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

18,912

Solution 1

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.

Solution 2

You can just use the Scanner!

Scanner scn = new Scanner(new File("myFile.txt"));

Using the command line, you will use the parameters given in your psv main.

public static void main(String args[]) {

    Scanner scn = new Scanner(new File(args[0]));
}

You can then run your .jar file from the command line, and pass it a path.

java -jar myJar.jar "/home/matt/myFile.txt"

In Eclipse, you can go into your launch configuration edtor, and manualy specify arguments to be added on launch, from within Eclipse.

Share:
18,912
user1010101
Author by

user1010101

Updated on June 05, 2022

Comments

  • user1010101
    user1010101 almost 2 years

    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

  • user1010101
    user1010101 over 9 years
    exactly what i was looking for ! makes my life easy.
  • user1010101
    user1010101 over 9 years
    Yea this saves me a ton of time i can easily feed large input file to my algorithms and check for desired output.