如何将 InputStream 转换为虚拟文件

我有一个方法,它期望输入变量之一是 java.io。文件类型,但我得到的只是 InputStream。而且,我不能更改该方法的签名。

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

110220 次浏览

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.

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.

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;
}


}

If you want to use the MultiPartFile in testing like getting a document from the resource folder -- you can use this.

import org.springframework.mock.web.MockMultipartFile;




ClassLoader classLoader = SomeClass.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(BASE_DIR + fileName);
MockMultipartFile("file", "NameOfTheFile", "multipart/form-data", inputStream);