Java 如何向输出中添加行号并检测文件是否为';没有找到?

Java 如何向输出中添加行号并检测文件是否为';没有找到?,java,filereader,Java,Filereader,我的代码应该从用户处接收文件名,并将内容输出到一个编号列表中,如下所示: 现在,我似乎无法添加1。2.3等输入到我的输出中,而无需硬编码,或者我如何尝试检测文件是否与代码文件位于同一目录中,并告诉用户该文件不存在 到目前为止,我已经正确地输出了代码,如示例所示,但减去了文件内容的编号或区分用户输入的文件是否存在 import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util

我的代码应该从用户处接收文件名,并将内容输出到一个编号列表中,如下所示:

现在,我似乎无法添加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());
        }

    }
}

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

如果我正确理解您的要求,您希望为用户指定的文件的每一行打印行号

如果是这样,那么在逐行读取文件时,只需添加一个
计数器
变量即可:

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());
        }

    }
}

我还添加了一个检查,以查看使用该方法的
文件是否存在。

这正是我所需要的。非常感谢。