import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ByteArrayTest2 {
    public static void main(String[] args) throws IOException {
        
        byte[] b = getBytesFromFile("test.txt");
        
        toFileFromBytes(b);
        
        String s = new String(b);
        
        System.out.println(s);
        
    }
    
    public static byte[] getBytesFromFile(String fileName) throws IOException{
        byte[] dest = null;
        
        InputStream is = new BufferedInputStream(new FileInputStream(fileName));
        
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        
        byte[] buff = new byte[1024];
        int len = 0;
        while((len=is.read(buff))!=-1){
            System.out.println(len);
            out.write(buff, 0, len);
        }
        
        dest = out.toByteArray();
        out.close();
        is.close();
        return dest;
    }
    
    
    public static void toFileFromBytes(byte[] b) throws IOException{
        InputStream is = new BufferedInputStream(new ByteArrayInputStream(b));
        
        OutputStream out = new BufferedOutputStream(new FileOutputStream("toFileFromBytes.txt"));
        
        byte[] buff = new byte[1024];
        int len = 0;
        while((len=is.read(buff))!=-1){
            System.out.println(len);
            out.write(buff, 0, len);
        }
        out.flush();
        out.close();
        is.close();
    }
    
}

 

posted on 2016-10-24 21:03  woqiaoxun  阅读(365)  评论(0编辑  收藏  举报