读书人

Java语言中惯用的io类

发布时间: 2012-12-26 14:39:29 作者: rapoo

Java语言中常用的io类
Java语言中常用的io类(处理流)
1.BufferedInputStream 和 BufferedOuputStream
2.TransformInputStream 和 TransformOutputStream
3.DataInputStream 和 DataOutputStream
4.ByteArrayInputStream 和 ByteArrayOutputStream
5.PrintStream 和 PrintWriter
6.ObjectInputStream 和 ObjectOutputStream


先来个ObjectIO实例,其他以后再补
1.ObjectInputStream和ObjectOutputStream
主要是对对象的写入与读取操作,也可用于网络的数据传输
实例:

package com.zkl.objectio;/** * 通过ObjectOutputStream存储的对象必须是可以序列化的 * 而对象必须实现Serializable接口,以标记该对象是可以序列化的。 * Serializable接口没有实现的方法,只是作为序列化标记。 * @author zkl1 * */import java.io.*;import java.util.*;public class ObjectIOTest {/** * 数据对象写入文件 * @param objs * @param filename */public void writeObjectToFile(Object[] objs,File filename){File file = filename;try {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));for(Object obj:objs){oos.writeObject(obj);}oos.close();} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}}/** * 从文件中读取数据对象 * @param filename * @return * @throws FileNotFoundException */public Object[] readObjectFromFile(File filename) throws FileNotFoundException{File file = filename;if(!file.exists()){throw new FileNotFoundException();}//定义一个只存储Student对象的泛型List容器//List<Student> list = new ArrayList<Student>();List list = new ArrayList();try {FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis);while(fis.available()>0){//list.add((Student)ois.readObject());list.add(ois.readObject());}fis.close();ois.close();} catch (Exception e) {// TODO: handle exception}return list.toArray();}/** * 将数据对象添加到文件的未尾 * @param objs * @param filename * @throws FileNotFoundException */public void appendObjectToFile(Object[] objs,File filename) throws FileNotFoundException{File file = filename;//如果文件不存在,则抛出异常if(!file.exists()){throw new FileNotFoundException();}try {//不写入标示头,重写writeStreamHeader()函数ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file,true)){protected void writeStreamHeader(){}};for(Object obj:objs){oos.writeObject(obj);}oos.close();} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubFile file = new File("c:\\data.dat");ObjectIOTest oit = new ObjectIOTest();Object stu[] = {new Student("zkl",12345), new Student("中国星",5677), new Student("china34420",8201868)};oit.writeObjectToFile(stu, file);try {Object objs[] = oit.readObjectFromFile(file);Student st;for(int i=0;i<objs.length;i++){if(objs[i] instanceof Student){st = (Student)objs[i];st.showData();}}Object st2[] = {new Student("dd",33),new Student("eeee",444) };oit.appendObjectToFile(st2, file);System.out.println();objs = oit.readObjectFromFile(file);for(Object obj:objs){((Student)obj).showData();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

读书人网 >编程

热点推荐