I need to be able to choose any file inside a folder by input on console.
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.
Say you have specified a folder, or use the current working directory.
At least you need two ingredients:
Search for [java] list files in directory
and pick:
File[] files = directory.listFiles();
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();