-2

I dont really know how to express my words but here's the output example.

Please enter the desired folder: c:/Test

a.txt b.txt c.txt d.txt

Enter the name of the file that you want to run: a.txt

Hello Java!

And if I put the file with nothing in it, the output will be

The file is empty. Start again.

Community
  • 1
  • 1

2 Answers2

1

You are so lazy to google the basics.
I'll help you:
1. Get directory content:How to get contents of a folder and put into an ArrayList
2. Output file content: How do you read a text file and print it to the console window? Java and How to write console output to a txt file

Consider googling an 'if-else' situations.
Hope this will help!

Community
  • 1
  • 1
tmn4jq
  • 351
  • 1
  • 3
  • 12
0

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)

Monis
  • 918
  • 7
  • 17