【问题标题】:having issues with Java reading input files using netbeansJava 使用 netbeans 读取输入文件时遇到问题
【发布时间】:2017-10-17 21:20:38
【问题描述】:

以下是我正在为一个学校项目编写的代码。在我尝试阅读 animal.txt 文件之前,它确实没问题。有人可以告诉我我做错了什么吗?我将我的编译错误作为图像附加。提前致谢。

[输入错误图片1

   package finalproject;

      //enabling java programs
      import java.util.Scanner;
      import javax.swing.JOptionPane;

导入 java.io.FileInputStream; 导入 java.io.IOException;

公共类监控{

public static void choseAnimal() throws IOException{
    FileInputStream file = null;
    Scanner inputFile = null;
    System.out.println("Here is your list of animals");
     file = new FileInputStream("\\src\\finalproject\\animals.txt");
     inputFile = new Scanner(file);

    while(inputFile.hasNext())
    {
        String line = inputFile.nextLine();
        System.out.println(line);
    }
}

 public static void choseHabit(){
System.out.println("Here is your list of habits");

}


public static void main(String[] args) throws IOException{
    String mainOption = ""; //user import for choosing animal, habit or exit
    String exitSwitch = "n"; // variable to allow exit of system
    Scanner scnr = new Scanner(System.in); // setup to allow user imput




    System.out.println("Welcome to the Zoo");
    System.out.println("What would you like to monitor?");
    System.out.println("An animal, habit or exit the system?");
    mainOption = scnr.next();
    System.out.println("you chose " + mainOption);
    if (mainOption.equals("exit")){
    exitSwitch = "y";
    System.out.println(exitSwitch);
    }
    if (exitSwitch.equals( "n")){
        System.out.println("Great, let's get started");
    }
        if (mainOption.equals("animal")){
            choseAnimal();

        }
        if (mainOption.equals("habit")) {
            choseHabit();

        }

    else {
        System.out.println("Good bye");
    }

}

}

【问题讨论】:

  • 永远不要在你的代码中引用src,一旦程序被构建和打包,它就不会存在了。 Netbeans自动将src目录下的所有东西打包到结果jar文件中
  • 你也不能把这种类型的资源当作文件,你需要使用Class#getResourceClass#getResourceAsStream才能读取它

标签: java file input netbeans


【解决方案1】:

\\src\\finalproject\\animals.txt 表明该文件是嵌入式资源。

首先,你不应该在你的代码中引用src,一旦程序被编译和打包,它就不会存在了。

其次,您需要使用Class#getResourceClass#getResourceAsStream才能阅读。

有点像……

//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);

try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
    //...
} catch (IOException exp) {
    exp.printStackTrace();
}

例如

现在,这假设文件 animals.txt 存在于 finalproject 包中

【讨论】:

    【解决方案2】:

    错误信息清楚地表明它找不到文件。这意味着有两种可能性:

    1. 文件在您想要的目录中不存在
    2. 你想要的目录不是你拥有的目录。

    我将首先创建一个File 对象,查看"."(当前目录)并打印它以查看默认情况下它的目录。您可能需要硬编码文件路径,具体取决于 netbeans 用于默​​认目录的内容。

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 2015-05-23
      • 2023-01-04
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多