package IODemo;import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;/*** @author Alina* @date 2021年11月08日 9:13 下午* 把Arraylist 里存储的内容存储到本地文件* 1.遍历集合。遍历一次存储一次*/
public class IOtest {public static void main(String[] args)throws Exception {CreadArraylist();readtxt();}// 创建数据存入集合public static void CreadArraylist()throws Exception{ArrayList<People> arrayListOne = new ArrayList<>();arrayListOne.add(new People("001","张三",18) );arrayListOne.add(new People("002","李四",20) );arrayListOne.add(new People("003","王二",21) );arrayListOne.add(new People("004","麻子",94) );arrayListOne.add(new People("005","李四",29) );arrayListOne.add(new People("006","王五",9) );//创建输出流BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/IODemo/people.txt"));//创建集合的迭代器Iterator<People> it = arrayListOne.iterator();while (it.hasNext()){bos.write(it.next().toString().getBytes(StandardCharsets.UTF_8));bos.write("\n".getBytes(StandardCharsets.UTF_8));}bos.close();}//读取文件中内容public static void readtxt() throws Exception{//创建读入流BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src/IODemo/people.txt"));//创建集合ArrayList<People> read_arraylist = new ArrayList<>();byte [] bytes = new byte[1024];int num = 0;while ((num=bis.read(bytes)) != -1){System.out.print(new String(bytes,0,num));}}}
package IODemo;/*** @author Alina* @date 2021年11月08日 9:22 下午*/
public class People {String ID;String name ;int age;public People(String ID, String name, int age) {this.ID = ID;this.name = name;this.age = age;}public String toString(){return getID()+" "+getName()+" "+getAge();}public String getID() {return ID;}public void setID(String ID) {this.ID = ID;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}