首页 > 解决方案 > 打印指定文件练习 Java

问题描述

参加 Java 初学者课程,我被困在其中一个练习上。我们的目的是打印特定文件中的文本,我们可以通过用户输入的文件名找到该文件。在之前的练习中,我们了解到

    try(Scanner scanner = new Scanner(Paths.get("data.txt")))

会在文件“data.txt”中找到文本,但我不确定如何将其转换为查找用户输入的任何文件名。

更多详情如下。

练习:编写一个程序,询问用户一个字符串,然后打印一个名称与提供的字符串匹配的文件的内容。您可以假设用户提供了程序可以找到的文件名。

练习模板包含文件“data.txt”和“song.txt”,您可以在测试程序功能时使用它们。当用户输入字符串“song.txt”时,程序的输出如下所示。打印的内容来自文件“song.txt”。自然,该程序也应该使用其他文件名,假设可以找到该文件。

到目前为止,我的代码是:

    import java.nio.file.Paths;
    import java.util.Scanner;

    public class PrintingASpecifiedFile {

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.println("Which file should have its contents printed?");
    
            String fileName = scanner.nextLine();
    
          //try(Scanner scanner = new Scanner(Paths.get(fileName))) {
            try(scanner = Paths.get(fileName)) {    // this part of the code is underlined red
        
                while (scanner.hasNextLine()){
                    String output = scanner.nextLine();
                    System.out.println(output);
                }
        
            } 
            catch (Exception e){
                  System.out.println("Error: " + e.getMessage());
            }

          }
       }

我曾尝试搜索如何添加新扫描仪,因为这是一个建议,但每次我尝试它都会出错。“尝试”部分也带有红色下划线,似乎无法弄清楚原因。带下划线的红色部分表示try-with-resources 中的变量在 -source 8 中不受支持

如果有人有提示,我将不胜感激!谢谢!

标签: javaprinting

解决方案


您使用了一个Scanner从控制台读取文件路径。

您需要其他 Scanner(或阅读器替代品)来阅读文件。

try (Scanner fileScanner = new Scanner(fileName)) {
try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {

推荐阅读