1

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.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Dylan
  • 23
  • 4
  • This kind of thing is impractical without a gui. Why no gui? – g00se Aug 11 '21 at 17:46
  • A GUI (graphical user-interface) would make it easier, because Java has the [`JFileChooser`](https://www.tutorialspoint.com/swing/swing_jfilechooser.htm) dialog, that allows listing, filtering, choosing and returns the `File` choosen. – hc_dev Aug 11 '21 at 18:12
  • I know, but I have to use specifically a console :( – Dylan Aug 11 '21 at 18:17

1 Answers1

1

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();
hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • 1
    The `listFiles` method allows to pass a `FilenameFilter`, to list only specific files like `.png` images. – hc_dev Aug 11 '21 at 18:08