25

I am getting a a InputStream from getResourceAsStream(), and I managed to read from the file by passing the returned InputStream to a BufferedReader.

Is there any way I can write to the file as well?

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360

2 Answers2

37

Not directly, no - getResourceAsStream() is intended to return a view on read-only resources.

If you know that the resource is a writeable file, though, you can jump through some hoops, e.g.

URL resourceUrl = getClass().getResource(path);
File file = new File(resourceUrl.toURI());
OutputStream output = new FileOutputStream(file);

This should work nicely on unix-style systems, but windows file paths might give this indigestion. Try it and find out, though, you might be OK.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Unfortunately, I was not ok. I had to add a `toString()` to the `toUri()`: `new File(resourceUrl.toURI().toString());`. But now, a `FileNoFoundException` is being thrown in the third line: `"vfszip:\C:\jboss-5.1.0.GA\server\default\deploy\IMAss4.war\WEB-INF\classes\wservices\markers.txt (The filename, directory name, or volume label syntax is incorrect)"` – Andreas Grech May 09 '10 at 12:42
  • @Andreas: OK, that's JBoss's internal virtual filesystem getting in the way. This is why what you're trying to do is inadvisable. – skaffman May 09 '10 at 12:50
  • So then, is there any way I can put the file in the `Web Pages` folder and read/write to it from my Web Service? (Look at my question here for my structure of documents: http://stackoverflow.com/questions/2797162/getresourceasstream-is-always-returning-null) – Andreas Grech May 09 '10 at 12:52
11

Is there any way I can write to the file as well?

Who says it's a file? The whole point of getResourceAsStream() is to abstract that away because it might well not be true. Specifically, the resource may be situated in a JAR file, may be read from a HTTP server, or really anything that the implementer of the ClassLoader could imagine.

You really shouldn't want to write to a resource that's part of your program distribution. It's conceptually the wrong thing to do in most cases. Settings or User-specific data should go to the Preferences API or the user's home directory.

codepleb
  • 10,086
  • 14
  • 69
  • 111
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • Then is there a way I can access a file that is located where the jsp pages are? ie directly in the `Web Pages` folder? from the Web Service ie – Andreas Grech May 09 '10 at 12:27
  • 4
    This answer doesn't provide an answer. It should be a comment. – dgh Aug 22 '13 at 22:00