【问题标题】:Java,How to link menu and read file?Java,如何链接菜单和读取文件?
【发布时间】:2025-12-04 21:30:01
【问题描述】:

以下是我的代码,我尝试让用户输入文件名,但它一直告诉我找不到 txt。文件,但如果我使用 Scanner fileInput = new Scanner(new File("C:\Users\k3llvin\workspace\Programming02\bin\assignment02\sample-logfile1.txt")); 它工作正常。

public static void main(String args[]) throws IOException,FileNotFoundException
   {

     String time,uniqueName,inventory,softwareUpdate,policy;

     try {
         Scanner fileInput = new Scanner(System.in);
         System.out.print("Input the filename:");
         String filename = fileInput.nextLine();
         File inputFile = new File(filename);
         Scanner reader = new Scanner(inputFile);
            /*Scanner fileInput = new Scanner(new File(
                    "C:\\Users\\k3llvin\\workspace\\Programming02\\bin\\assignment02\\sample-logfile1.txt"));*/

         for (int i = 0; i < 28; i++)
            {
                time = fileInput.next();
                uniqueName = fileInput.next();
                inventory = fileInput.next();
                policy = fileInput.next();
                softwareUpdate = fileInput.next();


                Readfile thefile = new Readfile(time,uniqueName,inventory, policy,softwareUpdate);

                System.out.println(thefile);    
            }
            fileInput.close();

     }
     catch (FileNotFoundException fnfe) {
            System.out.println("Unable to locate the sample-logfile1.txt file for opening.");

        } catch (Exception otherExc) {
            // This could occur due to any "unchecked" exceptions occurring, such as incorrect data interpretation during reading.
            System.out.println("An unexpected error has occurred. Details for programmer:");
            otherExc.printStackTrace();
   }

}

【问题讨论】:

    标签: java


    【解决方案1】:

    当您创建文件输入文件时,您只是给构造函数一个字符串,构造函数需要文件的路径。这就是为什么当你硬输入文件路径时它会起作用的原因。

    试试改成

    String filename = fileInput.nextLine();
    File inputFile = new File(filename);
    inputFile=inputFile.getAbsolutePath();
    Scanner reader = new Scanner(inputFile);
    

    【讨论】: