getResourceAsStream() in reverse to create a file

R

Roger Varley

Hi

I'm having a bad day today! I know I can find a file in a directory
relative to my calling class with
this.getClass().getResourceAsStream(), but how do I do this in reverse
to create a file in a directory relative to my calling class?

Regards
Roger
 
T

Thomas Fritsch

Roger said:
Hi

I'm having a bad day today! I know I can find a file in a directory
relative to my calling class with
this.getClass().getResourceAsStream(), but how do I do this in reverse
to create a file in a directory relative to my calling class?

Regards
Roger
You can instead use
URL url = this.getClass().getResource("bla.txt");
// this only creates the URL, but doesn't check if it really exists

and then try open it for writing
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
...

But be aware that this won't work for read-only URL's, for example
because it points into a jar-file (jar:....) or into the web
(http://www.something...)
You should also check the javadoc for URL and URLConnection.
 
T

Thomas Weidenfeller

Roger said:
I'm having a bad day today! I know I can find a file in a directory
relative to my calling class with
this.getClass().getResourceAsStream(),

Almost. You get a stream for a resource. That resource (expressed by a
URL, see getResource()) might or might not be an individual file. It is
just something which can deliver a stream of bytes. How that stream of
bytes is delivered depends entirely on the classloader in use.
but how do I do this in reverse
to create a file in a directory relative to my calling class?

You can't in a simple and general way. Java does not provide a generic
mechanism to write something back to a resource, because it might simply
be impossible (e.g. the jar/zip format makes it very difficult to insert
a file into an existing jar/zip, or a web server doesn't allow to create
new web pages from the outside). You could try and start to mess around
with an URL as returned by getResource("some_dummy_name"), e.g. trying
to figure out if it is a file resource and extracting the directory part
from it, but that is a risky hack.

You are much better off with using properties files relative to the
user's home directory or the preference api. This would also make it
easier to ensure that your application works in a multiuser-environment.

/Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top