【发布时间】: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#getResource或Class#getResourceAsStream才能读取它