0

I'm able to read a file by specifying the file path (which is in my src project) but I'm trying to read or open it by providing its name when the user is prompted by the command line in the first argument.

File fileName = new File("/Users/blad/Documents/CS2/Labs/Project01/input.txt");
        try {
            Scanner sc = new Scanner(fileName);
            while(sc.hasNextLine()){

                System.out.println(sc.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 

The name of the file is "input.txt" Is there a way to approach that? Thank you.

Bladimir Baez
  • 66
  • 1
  • 1
  • 6

2 Answers2

0

you could try using these codes for a different approach and see if this would be able to fix your problem

FileReader fr = new FileReader("C:/Users/OCMEngineering1/Desktop/library/library/textfile/student.txt");
LineNumberReader lnr = new LineNumberReader(fr);
Archie Azares
  • 125
  • 11
0

Try this - it will read file name and then use it to create file object.If you want to read multiple file name use a while loop.

Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File fileName = new File(input);
sanky jain
  • 873
  • 1
  • 5
  • 14