开发者社区> 问答> 正文

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

我有应该从用户那里接收文件名并在如下编号列表中输出内容的代码: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 404 0
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
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载