我在Intellij中有一个简单的JavaEE Web应用程序项目,我需要读取src.main.resources
文件夹中的文件。以下是我的项目的截图。
我需要在getData()
函数中返回 data.txt 文件的上下文。当前方法除了将“Error”返回到index.jsp并抛出NoSuchFileException
之外什么都不做。我使用以下路径测试但结果是相同的。
"data.txt"
"/data.txt"
"src/main/resources/data.txt"
"/src/main/resources/data.txt"
非常感谢任何帮助。
答案 0 :(得分:1)
System.out.println("get data");
String newMessage = "error";
String fileName = "abc.txt";
try {
newMessage = new String(Files.readAllBytes(Paths.get("C:\\Users\\kalingay\\IdeaProjects\\SpringMVCCrudApp\\src\\main\\resources\\" + fileName)), "UTF-8");
System.out.println("out--->" + newMessage) ;
} catch (Exception e) {
System.out.println("Exception-->" + e);
}
答案 1 :(得分:1)
System.out.println("get data");
StringBuilder out = new StringBuilder();
try {
InputStream inputStream = HelloWorld.class.getResourceAsStream("kky.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
reader.close();
System.out.println("out--->" + out);
} catch (Exception e) {
System.out.println("Exception-->" + e);
}
确定HelloWorld类和kky.txt在同一个文件夹中... :) :)这会帮助你:) :)
使用相对路径.... :) :)试试这个
答案 2 :(得分:1)
首先,正确创建java项目结构,将HelloWorld.java放在src / main / java下。
将您的资源放在/ src / main / resources下。
使用以下内容加载资源:
public class Student
{
private int studentID;
private String firstName;
private String lastName;
private String email;
private int age;
private int[] grades;
public Student (int studentID, String firstName, String lastName, String email, int age, int grades[])
{
setStudentID(studentID);
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
setAge(age);
setGrades(grades);
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setAge(int age) {
this.age = age;
}
public void setGrades(int[] grades) {
this.grades = grades;
}
public int getStudentID() {
return studentID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return firstName + lastName;
}
public String getEmail() {
return email;
}
public int getAge() {
return age;
}
public int[] getGrades() {
return grades;
}
public int getAverageGrade() {
int averageGrade = 0;
for (int grade : grades) {
averageGrade += grade;
}
return averageGrade;
}
public void print() {
System.out.println(
"Student Name:\t" + getFullName() + "\n " +
"Student ID:\t" + getStudentID() + "\n" +
"Email:\t" + getEmail() + "\n" +
"Age:\t" + getAge() + "\n" +
"Average Grade:\t" + getAverageGrade()
);
}
}
答案 3 :(得分:0)