• 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. }

  • 相关阅读:
    网络基础知识
    使用QMetaObject::invokeMethod来发射信号
    网络安全(黑客)自学
    Leetcode75颜色分类
    准备蓝桥杯的宝贝们看过来,二分法一网打尽(基础篇)
    Servlet——进阶
    linux环境下查询主板、CPU、内存等硬件信息
    Spring Boot3 系列:Spring Boot3 跨域配置 Cors
    2022牛客多校#6 C. Forest
    2个小时的腾讯面试经历(C++),来看看它终究考察了些什么?
  • 原文地址:https://blog.csdn.net/m0_37566009/article/details/134029119