java - 尝试读取 txt 文件并将它们转换为具有不同原语的对象
问题描述
我正在尝试编写一种方法,该方法使用阅读器从纯 txt 文件(学生 id-学生姓名-学生姓氏)中读取学生详细信息,并创建并返回相应的新学生对象。. txt 文件逐行包含详细信息。学生证在一行,名字在下一行。
我试图在方法 readStudent() 中做到这一点
class StudentInputStream{
BufferedReader in;
public StudentInputStream(InputStream input) {
in = new BufferedReader(new InputStreamReader(input));
}
@Override
public void close() throws IOException {
in.close();
}
public Student readStudent() throws IOException {
/*Student student1 = new student();*/
return null;
}
}
解决方案
代码是不言自明的,如果您有任何问题,请告诉我。
File file = new File("Your file's path");
Scanner sc=null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayList<Student> list = new ArrayList<>();
while(sc.hasNextLine()){
if(sc.nextLine().equalsIgnoreCase("student")){
//Assuming each property is in the seperate line of file
String id,name,surname=null;
if(sc.hasNextLine()){
id = sc.nextLine();
/*if id is int use
* int id = Integer.parseInt(sc.nextLine());
*/
}
if(sc.hasNextLine()){
name = sc.nextLine();
}
if(sc.hasNextLine()){
surname = sc.nextLine();
}
list.add(new Student(id,name,surname));
}
}
使用缓冲读取器:
InputStream in = new FileInputStream("Your file's path");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
ArrayList<Student> list = new ArrayList<>();
while((str=br.readLine())!=null){
if(str.equalsIgnoreCase("student")){
String id=null,name=null,surname=null;
if((str=br.readLine())!=null){
id = str;
/*if id is int use
* int id = Integer.parseInt(sc.nextLine());
*/
}
if((str=br.readLine())!=null){
name = str;
}
if((str=br.readLine())!=null){
surname = str;
}
list.add(new Student(id,name,surname));
}
}
使用 ObjectInputStream
OutputStream out = new FileOutputStream("yourfilepath.bin");
ObjectOutputStream outputStream = new ObjectOutputStream(out);
Student s1 = new Student("100383", "JOHN", "MITCHELL");
Student s2 = new Student("100346", "AMY", "CHING");
outputStream.writeObject(s1);
outputStream.writeObject(s2);
outputStream.writeObject(null);//to realize that you reach the end of file
outputStream.close();
out.close();
InputStream in = new FileInputStream("yourfilepath.bin");
ObjectInputStream inputStream = new ObjectInputStream(in);
Student temp = null;
while((temp =(Student)inputStream.readObject())!=null){
System.out.println(temp.id+","+temp.name+","+temp.surname);
}
输出
100383,约翰,米切尔
100346,艾米,清
推荐阅读
- django - 在 django 中获取表单值(外键字段)
- python - Python 修补来自导入模块的函数
- ios - 缩小相机 - Xcode Object Capture API
- excel - 在excel中将表格转换为不同的格式
- c++ - 在二进制文件中查找一个数字,旋转和覆盖
- typescript - 将值传递给抽象类的最佳方法是什么?
- sql-server - 避免 MSSQL 中的多个左连接
- sql - 如何在 Postgres 中返回 Null 而不是什么都没有?
- powershell - 有没有办法以高性能的方式在大量 SMB 共享上运行 Get-SMBShareAccess?
- c# - 端口被阻塞时连接到共享主机上的 Websocket