字符输出流,转换流,对象输入/输出流

来源:互联网 发布:淘宝买家福利晒图 编辑:程序博客网 时间:2024/06/10 10:17
private static void objectInputStream() {// TODO Auto-generated method stubtry {FileInputStream fis=new FileInputStream("c:\\hello.txt");ObjectInputStream ois=new ObjectInputStream(fis);List<Student> list=(List<Student>) ois.readObject();for(Student s:list){System.out.println(s.getStuid()+" "+s.getStuName());}ois.close();fis.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static void objectOutputStream() {// TODO Auto-generated method stub//创建list集合并添加数据List<Student> list=new ArrayList<Student>();list.add(new Student("01","李白"));list.add(new Student("02","李商隐"));try {//文件输出流创建对象,创建对象输出流FileOutputStream fos=new FileOutputStream("c:\\hello.txt");ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(list);//将对象写进文件oos.close();fos.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static void inputStreamRead() {// TODO Auto-generated method stubInputStreamReader isr=new InputStreamReader(System.in);//转换流,把字节流转换为字符流BufferedReader br=new BufferedReader(isr);//读取进逐行流String str = null;try {str = br.readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(str);try {br.close();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}try {isr.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static void fileWriter() {// TODO Auto-generated method stubtry {FileWriter fw=new FileWriter("c:\\hello.txt");//字符输出流BufferedWriter bw=new BufferedWriter(fw);//字符流读进逐行流bw.write("逐行流写");bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

对象类要实现序列化接口:

public class Student implements Serializable {private String stuid;private String stuName;public Student(String stuid, String stuName) {super();this.stuid = stuid;this.stuName = stuName;}public Student() {super();// TODO Auto-generated constructor stub}public String getStuid() {return stuid;}public void setStuid(String stuid) {this.stuid = stuid;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}}