天天看點

Java語言File,String, byte[]及File和MultipartFile互相轉化

概述

起因:在​​使用Selenium實作截圖​​時,發現API有三種方式生成截圖:

byte[] img = driver.getScreenshotAs(OutputType.BYTES);
String img = driver.getScreenshotAs(OutputType.BASE64);
File img = driver.getScreenshotAs(OutputType.FILE);      

于是有了三種方式互相轉化的需求。

String與byte[]互相轉化

最簡單:

// String to byte[]
byte[] aa = "ss".getBytes();
// byte[] to String
Arrays.toString(aa);      

String與File互相轉化

// File to String
public String fileToBase64(File file) {
    String base64 = null;
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        in.read(bytes);
        base64 = Base64.getEncoder().encodeToString(bytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return base64;
}

// String to File
public void base64ToFile(String destPath, String base64, String fileName) {
    File file;
    //建立檔案目錄
    File dir = new File(destPath);
    if (!dir.exists() && !dir.isDirectory()) {
        dir.mkdirs();
    }
    BufferedOutputStream bos = null;
    java.io.FileOutputStream fos = null;
    try {
        byte[] bytes = Base64.getDecoder().decode(base64);
        file = new File(destPath + "/" + fileName);
        fos = new java.io.FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(bytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}      

byte[]與File互相轉化

// byte[] to File
public void byte2File(byte[] buf, String filePath, String fileName) {
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    File file;
    try {
        File dir = new File(filePath);
        if (!dir.exists() && dir.isDirectory()) {
            dir.mkdirs();
        }
        file = new File(filePath + File.separator + fileName);
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(buf);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

// File to byte[]
public byte[] file2byte(File file) {
    byte[] buffer = null;
    try {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return buffer;
}      

File和MultipartFile互相轉化

File轉換成MultipartFile

需要引入依賴:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
</dependency>      

代碼:

FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.IMAGE_PNG.toString(), fileInputStream);      

MultipartFile轉換成File

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
</dependency>      
File file = new File(path); 
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);