带有 Scanner Java 的文件名



我已经成功地输入文件名并将其输出到控制台中。我唯一的问题是为什么我必须输入整个文件路径:

C:UsersAlekIdeaProjectsProject1srcInput1.txt

获取显示到输出的文件内容?为什么我不能只输入:

Input1.txt

显示文件的内容?下面是处理此任务的代码部分。

// Initialize variables
    Scanner keyboard  = new Scanner(System.in);     // Create Scanner object
    // Prompting user for the text file
    System.out.print("Enter the source path to the text file: ");
    String fileName = keyboard.nextLine();
    File file = new File(fileName); // Create File object

如果文件位于项目的根目录中,则可以只键入文件的名称。

Input1.txt移动到其父文件夹,因此其绝对路径变为:C:UsersAlekIdeaProjectsProject1Input1.txt

现在,您应该能够键入文件的名称而不是其路径。

最新更新