base64与文件转换

#base64引入

这里使用的是maven

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

#base64与String转换

@RequestMapping(value="/base64TextTest")
    public static void base64TextTest() throws IOException {
        final Base64 base64 = new Base64();
        final String text = "test";
        final byte[] textByte = text.getBytes("UTF-8");
        //编码
        final String encodedText = base64.encodeToString(textByte);
        System.out.println(encodedText);
        //解码
        System.out.println(new String(base64.decode(encodedText), "UTF-8"));
    }

#base64与文件转换

@RequestMapping(value="/base64FileTest")
    public static void base64FileTest() throws IOException {
        String base64String = null;
        InputStream in = null;
        final Base64 base64 = new Base64();
        String fileName = "D:/data/20191217145156.png";
        File file = new File(fileName);
        in = new FileInputStream(file);
        byte[] bytes=new byte[(int)file.length()];
        in.read(bytes);
     
base64String
= base64.encodeToString(bytes); System.out.println(base64String);
File file2 = null; //创建文件目录 String filePath="D:/data1"; File dir=new File(filePath); if (!dir.exists() && !dir.isDirectory()) { dir.mkdirs(); } BufferedOutputStream bos = null; java.io.FileOutputStream fos = null; String fileName2 = "new_file.png"; try { byte[] bytes1 = Base64.decodeBase64(base64String); file=new File(filePath+"/"+fileName2); fos = new java.io.FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes1); } 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(); } } }

猜你喜欢

转载自www.cnblogs.com/cmz-32000/p/12059791.html