对象类 package list; public class staff { private String num; private String name; private int age; public staff() { } public staff(String num, String name, int age) { this.num = num; this.name = name; this.age = age; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } 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; } }
集合到文件
package list; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class write { public static void main(String[] args) throws IOException { //创建ArrayList集合 ArrayListarray = new ArrayList (); //创建对象 staff s1 = new staff("001", "张三", 20); staff s2 = new staff("002", "李四", 22); staff s3 = new staff("003", "小明", 21); //把对象添加到集合中 array.add(s1); array.add(s2); array.add(s3); //创建字符缓冲输出流对象 BufferedWriter w = new BufferedWriter(new FileWriter("test\\namelist.txt")); //遍历集合,得到每一个对象 for (staff s : array) { //把对象的数据拼接成指定格式的字符串 StringBuilder Sp = new StringBuilder(); Sp.append(s.getNum()).append(",").append(s.getName()).append(",").append(s.getAge()); //调用字符缓冲输出流对象的方法写数据 w.write(Sp.toString()); w.newLine(); w.flush(); } //释放资源 w.close(); } }
生成的文件
文件到集合
package list; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class read { public static void main(String[] args) throws IOException { //创建字符缓冲输入流对象 BufferedReader r = new BufferedReader(new FileReader("test\\namelist.txt")); //创建ArrayList集合对象 ArrayListarray = new ArrayList (); //调用字符缓冲输入流对象的方法读数据 String line; while ((line = r.readLine()) != null) { //把读取到的字符串数据用split()进行分割,得到一个字符串数组 String[] strArray = line.split(","); //创建对象 staff s = new staff(); //把字符串数组中的每一个元素取出来对应的赋值给对象的成员变量值 s.setNum(strArray[0]); s.setName(strArray[1]); s.setAge(Integer.parseInt(strArray[2])); //把对象添加到集合 array.add(s); } //释放资源 r.close(); //遍历集合 for (staff s : array) { System.out.println(s.getNum() + "," + s.getName() + "," + s.getAge()); } } }
读取的结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)