Java 如何将 InputStream 转换为 FileInputStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2353057/
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-13 06:28:58  来源:igfitidea点击:

How to convert InputStream to FileInputStream

javafile-io

提问by Frank

I have this line in my program :

我的程序中有这一行:

InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");

But how can I get FileInputStream from it [Resource_InputStream] ?

但是我怎么能从中得到 FileInputStream [Resource_InputStream] 呢?

采纳答案by BalusC

Use ClassLoader#getResource()instead if its URI represents a valid local disk file system path.

ClassLoader#getResource()如果其 URI 表示有效的本地磁盘文件系统路径,请改用。

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

如果没有(例如 JAR),那么最好的办法是将它复制到一个临时文件中。

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStreaminstead of InputStream. If you can, just fix the API to ask for an InputStreaminstead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

也就是说,我真的没有看到这样做的任何好处,或者它必须由一个需要FileInputStream而不是InputStream. 如果可以,只需修复 API 以请求InputStream替代。如果是第 3 方,请务必将其报告为错误。在这种特定情况下,我还会在该 API 的其余部分周围加上问号。

回答by whiskeysierra

Long story short: Don't use FileInputStreamas a parameter or variable type. Use the abstract base class, in this case InputStream instead.

长话短说: 不要使用 FileInputStream作为参数或变量类型。使用抽象基类,在本例中为 InputStream。

回答by Nenad Bulatovic

You need something like:

你需要这样的东西:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

但它只能在您的 IDE 中工作,而不能在可运行的 JAR 中工作。我在这里解释了同样的问题。