gpt4 book ai didi

java - Java 使用 netbeans 读取输入文件时遇到问题

转载 作者:行者123 更新时间:2023-11-30 06:27:39 25 4
gpt4 key购买 nike

以下是我正在为学校项目编写的代码。在我尝试读取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\\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 包中

关于java - Java 使用 netbeans 读取输入文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com