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[] imgBytes = multipartFile.getBytes();
  • 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()

你可能感兴趣的:(Java,byte数组,InputStream,MultipartFile,OutputStream)