Search code examples
javafilechooserconsole-input

How do use console to choose any file from a folder?


I need to be able to choose any file inside a folder by input on console.

Code

Instead of a predefined like "bridge_rgb.png" I want to be able to choose any file in the folder via console input.

private void imageName() {
        System.out.println("Select your image");
        String input = scanner.next();
        if (input.equals("bridge_rgb.png")) {

        } else if (input.equals("gmit_rgb.png")) {
        
        }

        System.out.println("Image Selected");

    }

Inside my functions I want to do the same, here's the code:

File file = new File("bridge_rgb.png");
BufferedImage source = ImageIO.read(file);

// processing: result gets created

File output = new File("bridge_grey.png");
ImageIO.write(result, "png", output);

I know a GUI would make file-choosing easy, but I have to use specifically a console.


Solution

  • Say you have specified a folder, or use the current working directory.

    At least you need two ingredients:

    1. a function which lists all files given in the folder as option to choose from
    2. a user-interface (text-based or graphical) that allows to present those options and let the user choose from them (e.g. by hitting a number of clicking an item from a drop-down-list

    List files in current directory

    Search for [java] list files in directory and pick:

    File[] files = directory.listFiles();
    

    Text-based UI (TUI) to choose option by number

    E.g. from How can I read input from the console using the Scanner class in Java?

    // output on console
    System.out.println("Choose from following files:");
    for (int i=0, i < files.length(), i++) {
      System.out.println(String.format("[%d] %s", i, file.getName()); 
    }
    
    // reading the number
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    
    // testing if valid, within options index (0..n)
    if (i < 0 || i >= files.length()) {
      System.out.println("Invalid input. Please enter a number from options.");
    }
    // file choosen
    System.out.println("Your choice: " + file[i].getName());
    
    // other UI operations, like display file, etc.
    
    // IMPORTANT: always close the stream/scanner when finished
    scanner.close();