Assuming you want to take console input and read ONLY txt files, you can try the following
Read Contents from File (if present)
public static void main(String... s)throws IOException {
String folderName = "C://Test//";
Scanner sc = new Scanner(System.in);
String fileName = sc.nextLine();
File file = new File(folderName+fileName);
if(file.exists() && file.isFile() && file.length() > 0) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} else {
System.out.println("This file is empty. Start again");
}
}
Display hello java if file is found
public static void main(String... s)throws IOException {
String folderName = "C://Test//";
Scanner sc = new Scanner(System.in);
String fileName = sc.nextLine();
File file = new File(folderName+fileName);
if(file.exists() && file.isFile() && file.length() > 0) {
System.out.println("Hello Java!");
} else {
System.out.println("This file is empty. Start again");
}
}
The program will run, and you can input your desired filename (with .txt extension)