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

  • 相关阅读:
    XSS-labs靶场实战(二)——第4-6关
    UsernamePasswordAuthenticationFilter执行流程
    IVX低代码平台——小程序微信红包的应用的做法
    KT6368A蓝牙芯片的天线注意事项_倒F型-蛇形_陶瓷天线的区别
    h5修改钉钉双标题栏问题
    谷粒商城 高级篇 (十五) --------- 登录与注册
    计算机网络-网络层详细讲解
    双网卡多网卡时win11如何设置网卡优先级
    SpringMVC之JSON返回&异常处理机制
    我们这一代人的机会是什么?
  • 原文地址:https://blog.csdn.net/m0_37566009/article/details/134029119