欢迎来到[小脾气]的博客

做人要像铜钱,内方外圆

byte[]和File相互转换

1.File转byte[]

    /**
     * 文件转byte数组
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[] fileToByte(File file) throws IOException{
        FileInputStream in = new FileInputStream(file);
        BufferedInputStream bf = new BufferedInputStream(in);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] bytes = new byte[2048000];
        int len = 0;
        while((len=in.read(bytes)) != -1){
            bout.write(bytes,0,len); 
        }
        byte[] fileBytes = bout.toByteArray();
        return fileBytes;
    }

2.byte[]转File

    /**
     * byte数组转文件
     * @param bytes
     * @return
     * @throws IOException 
     */
    public static File byteToFile(byte[] bytes,String path,String name) throws IOException{
        File dir = new File(path);  
        if(!dir.exists()&&!dir.isDirectory()){//判断文件目录是否存在  
            dir.mkdirs();  
        }
        
        File file = new File(path + "\\" + name);
        FileOutputStream fout = new FileOutputStream(file);
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        bout.write(bytes);
        return file;
    }

 

posted on 2018-08-08 10:03  嚯嚯,小脾气  阅读(3874)  评论(0编辑  收藏  举报

导航