Java 如何将 InputStream 转换为虚拟文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4317035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:48:11  来源:igfitidea点击:

How to convert InputStream to virtual File

javafileinputstream

提问by Ram

I have a method which expects the one of the input variable to be of java.io.File type but what I get is only InputStream. Also, I cannot change the signature of the method.

我有一个方法,它期望输入变量之一是 java.io.File 类型,但我得到的只是 InputStream。此外,我无法更改该方法的签名。

How can I convert the InputStream into File type with out actually writing the file on to the filesystem?

如何将 InputStream 转换为 File 类型而不实际将文件写入文件系统?

采纳答案by cobbzilla

Something like this should work. Note that for simplicity, I've used a Java 7 feature (try block with closeable resource), and IOUtils from Apache commons-io. If you can't use those it'll be a little longer, but the same idea.

像这样的事情应该有效。请注意,为简单起见,我使用了 Java 7 功能(具有可关闭资源的 try 块)和来自 Apache commons-io 的 IOUtils。如果你不能使用它们,它会更长一点,但同样的想法。

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamUtil {

    public static final String PREFIX = "stream2file";
    public static final String SUFFIX = ".tmp";

    public static File stream2file (InputStream in) throws IOException {
        final File tempFile = File.createTempFile(PREFIX, SUFFIX);
        tempFile.deleteOnExit();
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            IOUtils.copy(in, out);
        }
        return tempFile;
    }

}

回答by Jan Thom?

You can't. The input stream is just a generic stream of data and there is no guarantee that it actually originates from a File. If someone created an InputStream from reading a web service or just converted a String into an InputStream, there would be no way to link this to a file. So the only thing you can do is actually write data from the stream to a temporary file (e.g. using the File.createTempFile method) and feed this file into your method.

你不能。输入流只是一个通用的数据流,不能保证它实际上来自文件。如果有人通过读取 Web 服务创建了 InputStream,或者只是将 String 转换为 InputStream,则无法将其链接到文件。因此,您实际上唯一能做的就是将数据从流写入临时文件(例如,使用 File.createTempFile 方法)并将此文件提供给您的方法。