开发者社区 问答 正文

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

我有应该从用户那里接收文件名并在如下编号列表中输出内容的代码: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());
        }

    }
}

注意:我对涉及文件的代码相当陌生,是的...

问题来源:Stack Overflow

展开
收起
montos 2020-03-26 15:36:47 427 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • 如果我理解正确的要求,则希望为用户指定的文件的每一行打印行号。

    如果是这样,那么您可以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存在使用该File.exists()方法。

    回答来源:Stack Overflow

    2020-03-26 15:37:21 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答地址:
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等