• NIO file 读取为字节数组


    1. import java.io.File;
    2. import java.io.FileInputStream;
    3. import java.io.FileNotFoundException;
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.io.OutputStream;
    7. import java.nio.ByteBuffer;
    8. import java.nio.channels.FileChannel;
    9. import org.apache.commons.codec.binary.Base64;
    10. public class Test {
    11. public static void main(String[] args) throws IOException {
    12. File f = new File("C:\\Users\\admin\\Desktop\\1\\2.png");
    13. byte[] datas = readByNIO(f);
    14. String encodeBase64String = Base64.encodeBase64String(datas);
    15. System.out.println(encodeBase64String);
    16. }
    17. public static byte[] readByNIO(File file) throws IOException {
    18. checkFileExists(file);
    19. //1、定义一个File管道,打开文件输入流,并获取该输入流管道。
    20. //2、定义一个ByteBuffer,并分配指定大小的内存空间
    21. //3、while循环读取管道数据到byteBuffer,直到管道数据全部读取
    22. //4、将byteBuffer转换为字节数组返回
    23. FileChannel fileChannel = null;
    24. FileInputStream in = null;
    25. try {
    26. in = new FileInputStream(file);
    27. fileChannel = in.getChannel();
    28. ByteBuffer buffer = ByteBuffer.allocate((int) fileChannel.size());
    29. while (fileChannel.read(buffer) > 0) {
    30. }
    31. return buffer.array();
    32. } finally {
    33. closeChannel(fileChannel);
    34. closeInputStream(in);
    35. }
    36. }
    37. private static void checkFileExists(File file) throws FileNotFoundException {
    38. if (file == null || !file.exists()) {
    39. System.err.println("file is not null or exist !");
    40. throw new FileNotFoundException(file.getName());
    41. }
    42. }
    43. private static void closeChannel(FileChannel channel) {
    44. try {
    45. channel.close();
    46. } catch (IOException e) {
    47. e.printStackTrace();
    48. }
    49. }
    50. private static void closeOutputStream(OutputStream bos) {
    51. try {
    52. bos.close();
    53. } catch (IOException e) {
    54. e.printStackTrace();
    55. }
    56. }
    57. private static void closeInputStream(InputStream in) {
    58. try {
    59. in.close();
    60. } catch (IOException e) {
    61. e.printStackTrace();
    62. }
    63. }
    64. }

  • 相关阅读:
    Windows(二):windows+nginx+openssl本地搭建nginx并配置ssl实现https访问
    Abp Vnext修改密码强度
    零束智能算法引擎赋能,打造数字座舱AI“大脑”
    【Centos】深度解析:CentOS下安装pip的完整指南
    实现 strStr()函数
    简单配置linux防火墙
    Excel第28享:如何新建一个Excel表格
    MongoDB设置密码
    Kubernetes 部署发布镜像(cubefile:0.4.0)
    Unity Xlua热更新框架(二):构建AssetBundle
  • 原文地址:https://blog.csdn.net/m0_37566009/article/details/134029119