在Java中Create a list of students by reading from student_hobbies.txt and display the list.
时间: 2024-02-29 14:53:07 浏览: 32
可以按照以下步骤来实现:
1. 创建一个名为Student的类,其中包含name和hobby两个属性。
```
public class Student {
private String name;
private String hobby;
public Student(String name, String hobby) {
this.name = name;
this.hobby = hobby;
}
public String getName() {
return name;
}
public String getHobby() {
return hobby;
}
}
```
2. 创建一个名为ReadFile的类,用于从文件中读取数据并返回一个Student列表。
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
public static List<Student> readStudentsFromFile(String fileName) {
List<Student> students = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
String name = parts[0];
String hobby = parts[1];
students.add(new Student(name, hobby));
}
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
}
```
3. 在主方法中调用ReadFile类的readStudentsFromFile方法,将学生列表打印出来。
```
public class Main {
public static void main(String[] args) {
List<Student> students = ReadFile.readStudentsFromFile("student_hobbies.txt");
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Hobby: " + student.getHobby());
}
}
}
```
这样就可以从student_hobbies.txt文件中读取学生信息,并打印出来了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)