文件转base64的多种方式

1、JDK1.7


import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.Objects;

public class Class01 {
    public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream("C:\\Users\\xxx\\Desktop\\abcdefg.mp3");
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        in.close();
        BASE64Encoder encoder = new BASE64Encoder();
        String result = encoder.encode(Objects.requireNonNull(bytes));
        File file = new File("C:\\Users\\xxx\\Desktop\\base64.txt");
        FileOutputStream outputStream;
        outputStream = new FileOutputStream(file);
        outputStream.write(result.getBytes());
        outputStream.close();
    }
}

2、JDK1.8(JDK1.8前的 sun.misc.BASE64Encoder类产生的base64有自动换行现象,影响解析。JDK1.8的Base64类没有自动换行现象)


import java.io.*;
import java.util.Base64;
public class Class01 {
    public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream("C:\\Users\\xxxx\\Desktop\\abcdefg.mp3");
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        byte[] encode = Base64.getEncoder().encode(bytes);
        String result = new String(encode);
        File file = new File("C:\\Users\\xxxx\\Desktop\\read02.txt");
        FileOutputStream outputStream;
        outputStream = new FileOutputStream(file);
        outputStream.write(result.getBytes());
        outputStream.close();
    }
}

3、maven库  common-codec

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.8</version>
    </dependency>
import org.apache.commons.codec.binary.Base64;
import java.io.*;
public class Class01 {
    public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream("C:\\Users\\xxxx\\Desktop\\abcdefg.mp3");
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        Base64 base64 = new Base64();
        String s = base64.encodeToString(bytes);
        File file = new File("C:\\Users\\xxxx\\Desktop\\read.txt");
        FileOutputStream outputStream;
        outputStream = new FileOutputStream(file);
        outputStream.write(s.getBytes());
        outputStream.close();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值