如何将InputStream转换为虚拟文件 [英] How to convert InputStream to virtual File

查看:146
本文介绍了如何将InputStream转换为虚拟文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,期望输入变量之一是java.io.File类型,但我得到的只是InputStream。我不能改变方法的签名。如何将InputStream转换成文件类型,实际上将文件写入文件系统?

解决方案

这样的东西应该可以工作。请注意,为了简单起见,我使用了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文件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;
}

}


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. I cannot change the signature of the method. How can I convert the InputStream into File type with out actually writing the file on to the filesystem?.

解决方案

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

}

这篇关于如何将InputStream转换为虚拟文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆