文件和byte数组之间相互转换

😂 这篇文章最后更新于1822天前,您需要注意相关的内容是否还可用。
目录导航
  • 文件转换成byte数组
    • 1. 传统方式
    • 或者
    • 2. NIO方式
  • byte数组转换成文件
    • 1. 传统方式
    • 2. NIO方式
  • 文件转换成byte数组

    文件转换成byte数组有两种方式:

    1. 传统方式

    File file = new File("/temp/abc.txt");
    FileInputStream fis = new FileInputStream(file);
    byte[] bytesArray = new byte[(int)file.length()]; //init array with file length
    fis.read(bytesArray); //read file into bytes[]
    fis.close();
    return bytesArray;

    或者

    File file = new File("D:/a.jpg");
    FileInputStream is=new FileInputStream(file);
    byte[] bytes=new byte[is.available()];
    is.read(bytes);
    is.close();

    2. NIO方式

    String filePath = "/temp/abc.txt";
    byte[] bFile = Files.readAllBytes(new File(filePath).toPath());
    //or this
    byte[] bFile = Files.readAllBytes(Paths.get(filePath));

    byte数组转换成文件

    byte数组转换成文件也有两种方式:

    1. 传统方式

    FileOutputStream fos = new FileOutputStream(fileDest);
    fos.write(bytesArray);
    fos.close();

    2. NIO方式

    Path path = Paths.get(fileDest);
    Files.write(path, bytesArray);

    作者:Java_Explorer
    链接:https://www.jianshu.com/p/b8b8f1ded401