代码之家  ›  专栏  ›  技术社区  ›  desau

从字节数组创建文件

  •  8
  • desau  · 技术社区  · 15 年前

    所以-我有一个第三方图书馆需要 File 作为输入。我有一个 byte array .

    文件 字节数组

    3 回复  |  直到 14 年前
        1
  •  10
  •   Michael Borgwardt    15 年前

    对不起,不可能。文件本质上是一个磁盘实体,除非你有一个RAM磁盘,但这不是用Java可以创建的东西。

        2
  •  3
  •   dty    15 年前

    有一种可能性,但可能性很小。

    如果API使用 new FileReader(file) new FileInputStream(file)

    如果它将文件转换为URL或URI(使用 toURL() toURI() File 不是final,可以传入 文件

    但是机会很渺茫!

        3
  •  0
  •   Wyetro    10 年前

    因此,我看到有一个公认的答案(这是古老的),但我找到了一个方法来做到这一点。我使用的是IDOL On Demand API,需要转换一个 byte array File

    下面是一个例子 把一个图像变成一个 文件

    //imageByte is the byte array that is already defined
    BufferedImage image = null;
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    image = ImageIO.read(bis);
    bis.close();
    
    // write the image to a file
    File outputfile = new File("image.png");
    ImageIO.write(image, "png", outputfile);
    

    所以呢 outputfile 是一个 文件