简体   繁体   中英

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. Or is it possible to convert the InputStream into an OutputStream that will point to the exact same file? I found out that getResourceAsStream() does not exist for OutputStream .

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). 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. In this case you should store the FILE externally (not in resources).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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