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

如何从ByteArrayOutputStream创建java.io.File?

  •  2
  • Tommy  · 技术社区  · 15 年前

    我正在从FTP读取一堆文件。然后我需要解压缩这些文件并将它们写入文件共享。

    我不想先写文件,然后再读回并解压缩它们。我想一气呵成。有可能吗?

    这是我的密码

    FTPClient fileclient = new FTPClient();
    ..
    
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    fileclient.retrieveFile(filename, out);
    
    ??????? //How do I get my out-stream into a File-object? 
    
    File file = new File(?);
    
    ZipFile zipFile = new ZipFile(file,ZipFile.OPEN_READ);
    

    6 回复  |  直到 15 年前
        1
  •  3
  •   Jack    15 年前

    你不需要创建 File 反对。

    如果要保存该文件,应将流直接管道到 ZipOutputStream

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(out);
    
    // do whatever with your zip file
    

    ZipInputStream :

    new ZipInputStream(fileClient.retrieveFileStream(String remote));
    

    读一下医生 here here

        2
  •  4
  •   Qwerky    15 年前

    你应该用 ZipInputStream InputStream 从返回 FTPClient retrieveFileStream(String remote)

        3
  •  2
  •   Dave Costa    15 年前

    我想你想要:

    ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
    

    然后从ZipInputStream读取数据。

        4
  •  1
  •   Stephen C    15 年前

    正如其他人所指出的,对于您正在尝试做的事情,您根本不需要将下载的ZIP“文件”写入文件系统。

    在Java中,a File 对象根本不表示文件。相反,它代表一个文件 名称

    这听起来可能有点像劈头,但请考虑以下情况:

    File dir = new File("/tmp/foo");
    boolean isDirectory = dir.isDirectory();
    if (isDirectory) {
        // spend a long time computing some result
        ...
        // create an output file in 'dir' containing the result
    }
    

    现在如果 文件 类表示文件系统中的对象,然后您将期望创建输出文件的代码成功(模块权限)。但事实上,创建可能会失败,因为有东西删除了“/tmp/foo”,或者用常规文件替换了它。

    一些 的方法 类似乎确实假定 文件

        5
  •  1
  •   Jon Skeet    12 年前

    你可以创造一个 FileOutputStream

    FileOutputStream fos = new FileOutputStream(filename);
    try {
      out.writeTo(fos);
    } finally {
      fos.close();
    }
    

    然后创建 File 对象:

    File file = new File(filename);
    

    文件 对象不表示磁盘上的任何实际数据—实际上,它只是一个文件名。文件甚至不必存在。如果你真的想 ,那就是 文件输出流 是为了。

    得到了 要做到这一点,如果您要将文件传递给需要真正的文件(其中包含数据)。

    如果你不想这样做,你必须使用一个不同的API 希望文件存在。。。根据Qwerky的回答。

        6
  •  0
  •   user207421    12 年前