在使用netbeans读取输入文件时遇到问题
问题描述:
以下是我正在为一个学校项目开发的代码。它没有问题,直到我尝试阅读animal.txt文件。有人可以告诉我我做错了什么吗?我将我的编译错误附加为图像。提前致谢。在使用netbeans读取输入文件时遇到问题
[输入误差图像1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
进口java.io.FileInputStream中; import 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");
}
}
}
答
显然错误消息表明,它无法找到该文件。这意味着有两种可能性:
- 文件不存在的目录,你想
- 你想目录是不是你的目录。
我将通过创建一个File
对象看"."
(当前目录)和打印的,看看它的外观目录默认启动。您可能需要对文件路径进行硬编码,具体取决于netbeans用于默认目录的路径。
答
\\src\\finalproject\\animals.txt
表明该文件是嵌入式资源。
首先,你永远不应该在你的代码中引用src
,一旦程序被构建和打包,它就不会存在。
其次,您需要使用Class#getResource
或Class#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
包存在
不要,曾经引用'src'在你的代码,程序一经构建和打包就不会存在。 Netbeans自动将'src'目录中的所有内容打包到结果jar文件中 – MadProgrammer
您也不能将这种类型的资源视为文件,您需要使用'Class#getResource'或'Class#getResourceAsStream'来阅读 – MadProgrammer