简体   繁体   English

有没有办法从 InputStream 获取文件

[英]Is there a way to get a file from InputStream

I'm currently reading a file with:我目前正在阅读一个文件:

InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream(FILE);

Is there any way I can get the file from this InputStream so that I can later write to it.有什么方法可以从这个InputStream获取文件,以便以后可以写入它。 Or is it possible to convert the InputStream into an OutputStream that will point to the exact same file?或者是否可以将InputStream转换为指向完全相同文件的OutputStream I found out that getResourceAsStream() does not exist for OutputStream .我发现OutputStream不存在getResourceAsStream()

You can do it with你可以用

File file = new File(MyClass.class.getResource(FILE).toURI());
FileOutputStream stream = new FileOutputStream(file);

It will work in IDE or if your app is a web app (war).它将适用于 IDE 或者如果您的应用程序是 web 应用程序(战争)。 But if you are writing a jar app, it will not work when you build it, because the file will be in jar package, you can not write it this way.但是如果你正在编写一个 jar 应用程序,它在你构建它时将不起作用,因为文件将在 jar package 中,你不能这样写。 In this case you should store the FILE externally (not in resources).在这种情况下,您应该将 FILE 存储在外部(而不是资源中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM