Java 二進制數據轉成文件


       SqlServer數據庫中,存儲文件的字段的類型是image,對應的Java類型是byte[],下面的函數將演示如何把讀取出來數據放入指定目錄。當然,首先需要從數據庫讀出,然后調用該方法。 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    /**
     * @Title: byteToFile
     * @Description: 把二進制數據轉成指定后綴名的文件,例如PDF,PNG等
     * @param contents 二進制數據
     * @param filePath 文件存放目錄,包括文件名及其后綴,如D:\file\bike.jpg
     * @Author: Wiener
     * @Time: 2018-08-26 08:43:36
     */
    public static void byteToFile(byte[] contents, String filePath) {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream output = null;
        try {
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(contents);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            // 獲取文件的父路徑字符串
            File path = file.getParentFile();
            if (!path.exists()) {
                logger.info("文件夾不存在,創建。path={}", path);
                boolean isCreated = path.mkdirs();
                if (!isCreated) {
                    logger.error("創建文件夾失敗,path={}", path);
                }
            }
            fos = new FileOutputStream(file);
            // 實例化OutputString 對象
            output = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1) {
                output.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            output.flush();
        } catch (Exception e) {
            logger.error("輸出文件流時拋異常,filePath={}", filePath, e);
        } finally {
            try {
                bis.close();
                fos.close();
                output.close();
            } catch (IOException e0) {
                logger.error("文件處理失敗,filePath={}", filePath, e0);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM