hc学习平台

 找回密码
 立即注册
搜索
热搜: 活动 交友 javakc
 › 学习交流 › JSE › 使用对象字节流操作学生信息(读写文件) 要求: 将以下学生信息写入到文件中 张三 20岁 ,李四 21岁,王五 22岁 先将学生信息封装在Student对象中,再多个Student对象封装在List集合中,最后将List集合保存在文件中。 从文件中把学生信息读取出来
查看: 207|回复: 0
打印 上一主题 下一主题

使用对象字节流操作学生信息(读写文件) 要求: 将以下学生信息写入到文件中 张三 20岁 ,李四 21岁,王五 22岁 先将学生信息封装在Student对象中,再多个Student对象封装在List集合中,最后将List集合保存在文件中。 从文件中把学生信息读取出来

[复制链接]

3

主题

0

帖子

1575

博客

naitizi

Rank: 9 Rank: 9 Rank: 9

积分

IP 编辑 禁止 帖子 清理

跳转到指定楼层
楼主
发表于2022-07-07 19:31:59 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
	
package com.jin;

import java.io.*;
import java.util.ArrayList;

public class InputStream {
    public static void main(String[] args) throws IOException {
        //创建ArrayList集合封装
        ArrayList<Student> array = new ArrayList<Student>();
        Student s1 = new Student("金赓砷", 22);
        Student s2 = new Student("宋梦丽", 18);
        Student s3 = new Student("田萌", 21);
        array.add(s1);
        array.add(s2);
        array.add(s3);
        //创建字符缓冲流
        BufferedWriter sb = new BufferedWriter(new FileWriter("E:\porject\project_demo1\copy.txt"));
        //增强for将Student写入文件,
        for (Student s : array) {
            StringBuilder dw = new StringBuilder();
            System.out.println(dw.append(s.getName()).append(",").append(s.getAge()));
            sb.write(dw.toString());
            sb.newLine();
            sb.flush();
        }
        //关闭流
        sb.close();
        //读文件
        BufferedReader br = new BufferedReader(new FileReader("E:\porject\project_demo1\copy.txt"));
        ArrayList<Student> arrayList = new ArrayList<Student>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] strarry = line.split(",");
            Student s =new Student();
            s.setName(strarry[0]);
            s.setAge(Integer.parseInt(strarry[1]));
            array.add(s);
        }
        br.close();
        for(Student s:arrayList){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}


站点统计|举报|Archiver|手机版|小黑屋|Comsenz Inc.

GMT+8, , Processed in 0.195171 second(s), 9 queries .

Powered by javakc! X1.0

© 2004-2014 javakc

f1208.com 备案号:京ICP备14030918号-1

返回顶部