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.

3
  • This kind of thing is impractical without a gui. Why no gui? Commented Aug 11, 2021 at 17:46
  • A GUI (graphical user-interface) would make it easier, because Java has the JFileChooser dialog, that allows listing, filtering, choosing and returns the File choosen. Commented Aug 11, 2021 at 18:12
  • I know, but I have to use specifically a console :( Commented Aug 11, 2021 at 18:17

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

The listFiles method allows to pass a FilenameFilter, to list only specific files like .png images.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.