IO流与对象结合
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;}}
總結
- 上一篇: absolute 必须 relative
- 下一篇: 为什么运营商的机顶盒(IPTV)看直播不