-3

I am trying to read a file from command line. I have wrote a code where i put my input file line like this.

 FileInputStream fis = new FileInputStream("C:/textfile.txt");

Instead i want to give the input file name in command prompt while running the java program. Could anyone help me how to do that? Thanks.

CrazyJava
  • 15
  • 7
  • 1
    Can you explain why the existing questions and tutorials didn't help? – Tom Nov 02 '15 at 15:30
  • 1
    You can use the `Scanner` class.. – Jos Nov 02 '15 at 15:31
  • 1
    If you mean command line arguments, they are in the `args[]` array: http://stackoverflow.com/questions/29859817/java-command-line-arguments-to-get-info – zapl Nov 02 '15 at 15:32
  • Because I didn't find the answer for my issue. And the duplicate question doesn't solve my issue. Anyway thanks for your responses. Thanks guys.. – CrazyJava Nov 09 '15 at 15:50

2 Answers2

0

use the below code

public static void main(String[] ar) {
    if (ar.length > 0) {
        String fileName = ar[0];
        if (null != fileName && !"".equals(fileName.trim())) {
            try {
                FileInputStream fis = new FileInputStream(fileName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            System.out
                    .println("Enter a file name ith command line argument.");
        }
    } else {
        System.out.println("Enter a file name ith command line argument.");
    }
}

While running the example run the following command

java className fileName
Vivek Singh
  • 2,047
  • 11
  • 24
0
Scanner s = new Scanner (System.in);//create a scanner object

String filePath= s.nextLine();//read nextLine input from consol.
FileInputStream fis = new FileInputStream(filePath);
QuakeCore
  • 1,886
  • 2
  • 15
  • 33