IO(三)字节流练习

public class ByteStreamDemo {
    
    /*
        int available();                         可以取得输入文件的大小(字节个数),没有返回0
        void close();                            关闭输入流
        abstract int read();                    读取一个字节,并把读到的字节返回,没有返回-1
        int read(byte[] b);                        将内容读到byte数组,并且返回读入的字节的个数。,没有返回-1
        int read(byte[] b ,int off ,int len);    将内容读到byte数组,从off开始读,读len个结束。,没有返回-1
     */
    
    
    /*
        public void close();                    关闭输出流。
        public void flush();                    刷新缓冲区。
        public void write(byte[] b);            将byte数组写入数据流
        write(byte[] b ,int off ,int len);        将指定范围的数据写入数据流。
        public abstract void write(int b);        将一个字节数据写入数据流
     */
    
    //输入流没有找到文件报异常,输出流没有文件会自动创建
    
    public static void executeByteFile(){
        File inFile = new File("D:"+File.separator+"intest.txt");
        File outFile = new File("D:"+File.separator+"outtest.txt");
        
        long start = System.currentTimeMillis();
        
        FileInputStream in = null;
        OutputStream out = null;
        try {
             in = new FileInputStream(inFile);
             //true表示在原文件上追加。
             out = new FileOutputStream(outFile,true);
            
            byte[] inb = new byte[1024];
            
            int size = 0;
            while ((size = in.read(inb)) != -1) {
//                System.out.println(new String(inb,0,size,"gbk"));
                out.write(inb, 0, size);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            CloseUtil.close(out);
            CloseUtil.close(in);
        }
        
        System.out.println("结束时间:"+(System.currentTimeMillis() - start));
    }
    
    
    /**操作字节数组的输入流
     * @throws IOException */
    public static void executeByteIn() throws IOException{
        final String str = "我爱中华!";
        byte[] bytes = str.getBytes();
        
        ByteArrayInputStream byin = new ByteArrayInputStream(bytes);
        byte[] db = new byte[3];
        int read = byin.read(db);
        while ( read !=-1 ) {
            String s = new String(db,0,read,"UTF-8");
            
            System.out.println(s);
            read = byin.read(db);
        }
        
        byin.close();
    }
    
    /**操作字节数组的输出流
     * @throws IOException */
    public static void executeByteOut() throws IOException{
        final String str1 = "我爱中华!";
        final String str2 = "字节数组输出流!";
        byte[] bytes1 = str1.getBytes();
        byte[] bytes2 = str2.getBytes();
        
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(bytes1);
        out.write(bytes2);
        
        //先把数据都写进字节数组输出流中。之后统一输出
        System.out.println(out.toString());
        out.close();
    }
    
    /** 管道流*/
    public static void executePip() throws IOException{
        PipedByteOut out = new PipedByteOut();
        PipedByteIn in = new PipedByteIn();
        out.getOut().connect(in.getIn());
        
        
        Thread inThread = new Thread(in,"thread-piped-in");
        Thread outThread = new Thread(out,"thread-piped-out");
        inThread.start();
        outThread.start();
    }
    
    /** 缓存字节流*/
    public static void executeBufferStream() throws Exception{
        File inFile = new File("D:"+File.separator+"intest.txt");
        File outFile = new File("D:"+File.separator+"outtest.txt");
        
        long start = System.currentTimeMillis();
        BufferedInputStream inbuffer = new BufferedInputStream(new FileInputStream(inFile));
        BufferedOutputStream outbuffer = new BufferedOutputStream(new FileOutputStream(outFile,true));
    
        byte[] inb = new byte[1024];
        
        int size = 0;
        while ((size = inbuffer.read(inb)) != -1) {
            
            outbuffer.write(inb, 0, size);
        }
        outbuffer.flush();
        CloseUtil.close(outbuffer);
        CloseUtil.close(inbuffer);
        System.out.println("结束时间:"+(System.currentTimeMillis() - start));
    }
    
    /** 对象流可以将对象序列化*/
    public static class SerializeUtil{
        
        public static byte[] serializeObject(Object object){
            ObjectOutputStream out = null;
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            
            try {
                out = new ObjectOutputStream(by);
                out.writeObject(object);
                return by.toByteArray();
            } catch (IOException e) {
                throw new RuntimeException("对象序列化错误");
            }finally{
                CloseUtil.close(by);
                CloseUtil.close(out);
            }
        }
        
        public static <T> T unSerialized(byte[] by){
            if(by == null || by.length == 0) return null;
            ByteArrayInputStream byin = null;
            ObjectInputStream in = null;
            try {
                 byin = new ByteArrayInputStream(by);
                 in = new ObjectInputStream(byin);
                return (T) in.readObject();
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException("对象反序列化错误");
            }finally{
                CloseUtil.close(in);
                CloseUtil.close(byin);
            }
        }
    }
    
    public static void main(String[] args) throws Exception{
        User user = new User();
        user.setAddres("地址");
        user.setId(1);
        user.setName("测试");
        
        byte[] bs = SerializeUtil.serializeObject(user);
        
        Object object = SerializeUtil.unSerialized(bs);
        System.out.println(object);
    
    }
}

class PipedByteIn implements Runnable{
    
    private PipedInputStream in = new PipedInputStream();
    
    @Override
    public void run() {
        try {
            
            byte[] by = new byte[1024];
            int i = in.read(by);
            while (i != -1) {
                System.out.println(new String(by,0,i,"UTF-8"));
                i = in.read(by);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            CloseUtil.close(in);
        }
    }
    
    public PipedInputStream getIn(){
        return in;
    }
}

class PipedByteOut implements Runnable{
    private PipedOutputStream out = new PipedOutputStream();
    
    @Override
    public void run() {
        byte[] bytes = "我爱中华!".getBytes();
        try {
            out.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            CloseUtil.close(out);
        }
    }
    
    public PipedOutputStream getOut(){
        return out;
    }
}

class User implements Serializable{

    private static final long serialVersionUID = 1L;
    
    private Integer id;
    private String name;
    //transient代表该字段不被序列化
    private transient String addres;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddres() {
        return addres;
    }
    public void setAddres(String addres) {
        this.addres = addres;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", addres=" + addres + "]";
    }
}
class CloseUtil{
    public static void close(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
posted @ 2016-04-13 16:58  姩澕  阅读(186)  评论(0编辑  收藏  举报