如何在输出中添加行号并检测是否找不到文件?

How can I add an line number to my output and detect if a file isn't found?

我的代码应该从用户那里接收文件名,然后将内容输出到编号列表中,如下所示: https://imgur.com/a/CGd86xU

现在,我似乎无法在不进行硬编码的情况下将 1.2.3. 等添加到我的输出中,或者我如何尝试检测是否在同一目录中找不到文件因为代码文件在并告诉用户这样的文件不存在。

到目前为止,我已正确输出代码,如示例所示,但减去文件内容的编号或区分用户输入的文件是否存在。

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
    public static void main(String[] args) throws IOException {
        try {

            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter filename");
            String fileName = scanner.nextLine();
            File f = new File(fileName);
            BufferedReader b = new BufferedReader(new FileReader(f));
            String readLine = null;
            System.out.println("");  //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.

            while ((readLine = b.readLine()) != null) {
                System.out.println(readLine);
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}

注意:我对涉及文件的代码比较陌生,所以是的...

如果我理解你的要求是正确的,你想为用户指定的文件的每一行打印行号。

如果是这样,那么你可以在逐行读取文件时添加一个counter变量:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
    public static void main(String[] args) throws IOException {
        try {

            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter filename");
            String fileName = scanner.nextLine();
            File f = new File(fileName);

            if (!f.exists()) { 
                System.out.println(fileName + " doesn't exist!");
                return;
            }

            BufferedReader b = new BufferedReader(new FileReader(f));
            String readLine = null;
            System.out.println("");  //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.

            int counter = 1;
            while ((readLine = b.readLine()) != null) {
                System.out.println(counter + ": " + readLine);
                counter++;
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}

我还使用 File.exists() 方法检查 File 是否存在。