0

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.

Yogesh Prajapati
  • 4,770
  • 2
  • 36
  • 77
Tymo Tymo
  • 93
  • 1
  • 6
  • Does this answer your question? [Is it possible to create a File object from InputStream](https://stackoverflow.com/questions/11501418/is-it-possible-to-create-a-file-object-from-inputstream) – silentsudo Jun 10 '20 at 06:34
  • No do not need to create a new file and then copy the contents. I want to get the exact same file that the inputstream is referencing. – Tymo Tymo Jun 10 '20 at 06:35
  • 2
    The InputStream doesn't have this information. More than that, a resource inside your application is not always even representable as a `File` – Felix Jun 10 '20 at 07:19

1 Answers1

-1

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).

Andrew Fomin
  • 244
  • 2
  • 8
  • This doesn't work if this resource is inside a JAR file, which is the usual case – Mark Rotteveel Jun 10 '20 at 08:24
  • There is no way to change resources in runtime. To edit file in jar archive you need to unpack it, rewrite file and pack it back. Even if you do these strange manipulations you won't be able to use the changed file, because JVM will have old jar loaded. – Andrew Fomin Jun 10 '20 at 14:10
  • I know that, that is why I commented that your answer won't work in most cases. – Mark Rotteveel Jun 10 '20 at 14:29
  • The point of my answer was 'you should store the FILE externally (not in resources)'. If someone missed it, I'm sorry – Andrew Fomin Jun 10 '20 at 15:55