views:

180

answers:

2

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?

+5  A: 

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
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
@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
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
+2  A: 

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.

Michael Borgwardt
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