您可以使用以下代码将文件内容转换为Student对象:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        filein();
    }

    public static void filein() throws FileNotFoundException {
        File file = new File("D:/file2/result2.txt");
        FileInputStream in = new FileInputStream(file);
        try {
            int size = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            String str = new String(buffer, "UTF-8");
            String[] studentData = str.split(";");
            for (String data : studentData) {
                String[] studentInfo = data.split("-");
                String name = studentInfo[0];
                int age = Integer.parseInt(studentInfo[1]);
                int score = Integer.parseInt(studentInfo[2]);
                Student student = new Student(name, age, score);
                System.out.println(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class Student {
    private String name;
    private int age;
    private int score;

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}

这段代码首先通过读取文件内容,将其转换为字符串。然后,使用分隔符将字符串拆分为每个学生的数据。再使用分隔符将每个学生的数据拆分为姓名、年龄和分数。最后,根据这些数据创建Student对象,并打印输出

public static void mainString args throws FileNotFoundException fileout; public static void fileout throws FileNotFoundException File file=new FileDfile2result2txt;FileOutputStream out=new Fi

原文地址: https://www.cveoy.top/t/topic/ipGA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录