How to convert InputStream to virtual File

前端 未结 2 1098
时光说笑
时光说笑 2020-11-29 02:27

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.

2条回答
  •  温柔的废话
    2020-11-29 02:47

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

提交回复
热议问题