Apacs
Apacs

Reputation: 9

Input file to java through command line

    public static void main(String[] args) throws IOException{          
            BufferedReader br = new BufferedReader(new FileReader("Input.txt"));
        }

I have to give input file through command line

java -cp  Projectfile.java < Input.txt

what change should I do in my program to fetch this file in BufferedReader?

Upvotes: 0

Views: 178

Answers (4)

CoolJavaProgrammer
CoolJavaProgrammer

Reputation: 55

First of all after initialising the BufferedReader class with "br" as its object, you need to write the following line

String str=br.readLine();
System.out.println(str);

Next you have to create a file Input.txt and place it in the same folder as that of your java file.

Next in the command prompt, write

javac Projectfile.java
Press Enter
java -cp . Projectfile < Input.txt

In this way it'll be done. Happy Coding Journey!!!

Upvotes: -1

dganesh2002
dganesh2002

Reputation: 2210

Try this way. You may optionally include 'else' part. If you dont want else part then move the bufferreader statement in 'then' part. Run it as ->

java -cp . Projectfile Input.txt

Code ->

public static void main(String[] args) throws IOException, {      
        String file;    
        if ( args.length > 0 ) {
           file = args[0];
        }
        //Optionally you can define the file name if not supplied in java command. 
        else {
           file = "Input.txt"
        }

        BufferedReader br = new BufferedReader(new FileReader(file));
    }

Upvotes: 1

Jubileu Tembe
Jubileu Tembe

Reputation: 41

try the code below:

public static void main(String [] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(args[0]));
}

During the execution of your program, you pass the file as argument but then you never use it. By using args[0], you will be using the argument that you passed on:

java -cp  Projectfile.java < Input.txt

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240870

You pass it as command line argument

java -cp  Projectfile.java Input.txt

and access passed argument in args[]

BufferedReader br = new BufferedReader(new FileReader(args[0]));

Upvotes: 1

Related Questions