天天看點

byte數組、Blob、inputStream、outputStream、MultipartFile之間的轉換

  • byte數組=>inputStream
byte[] b=new byte[1024];
ByteArrayInputStream inputStream=new ByteArrayInputStream(b);
           
  • inputstream=>byte數組
public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[1024];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 1024)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
           
  • outputStream=>byte數組
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] b=outputStream.toByteArray()
           
  • inputStream=>file
//Files是來自java.nio包
Files.copy(inputstream,Paths.get(”檔案的路徑“))
           
  • MultipartFile=>byte數組
  • byte數組=>MultipartFile
byte[] testFile = new byte[1024];
InputStream inputStream = new ByteArrayInputStream(testFile);
MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
           
  • inputStream => Blob

//Blob是java.sql.Blob

可通過Hibernate提供的API:Hibernate.createBlob(new FileInputStream(" 可以為圖檔/檔案等路徑 "))

  • Blob => InputStream
//Blob是java.sql.Blob
InputStream inputStream=blob.getBinaryStream()