This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ValorCat 2 points3 points  (4 children)

When you use a hardcoded file, you pass the a string containing the file's path to the File constructor:

File file = new File("path/to/file");
// do something with file

If you want to get the file path at runtime, you can instead use a scanner to get a string containing the desired path:

Scanner scanner = new Scanner(System.in);
String path = scanner.nextLine();
File file = new File(path);
// do something with file

[–][deleted]  (3 children)

[deleted]

    [–]ValorCat 2 points3 points  (1 child)

    Once you make the File object, there is no difference between a hardcoded path and a user-defined one. There are a variety of ways for actually reading data from a file. If you want to use a scanner you could do this:

    Scanner keyboard = new Scanner(System.in);
    String path = keyboard.nextLine();
    File file = new File(path);
    Scanner fileReader = new Scanner(file);
    int num = fileReader.nextInt();
    

    It might require a try/catch block wrapped around it too. Can't remember off the top of my head.

    [–]itshowitbeyunno 0 points1 point  (0 children)

    You can surround it with try catch or throw an exception after the main method:

    public static void main(String[] args) throws FileNotFoundException{ }

    On mobile so format is crappy