6

I have this strange thing with input and output streams, whitch I just can't understand. I use inputstream to read properties file from resources like this:

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream( "/resources/SQL.properties" );
rop.load(in);
return prop;

It finds my file and reds it succesfully. I try to write modificated settings like this:

prop.store(new FileOutputStream( "/resources/SQL.properties" ), null);

And I getting strange error from storing:

java.io.FileNotFoundException: \resources\SQL.properties (The system cannot find the path specified)

So why path to properties are changed? How to fix this? I am using Netbeans on Windows

1
  • 1
    Welcome to SO. +1 for a well-phrased question with all the appropriate information. Commented May 8, 2012 at 4:54

3 Answers 3

6

The problem is that getResourceAsStream() is resolving the path you give it relative to the classpath, while new FileOutputStream() creates the file directly in the filesystem. They have different starting points for the path.

In general you cannot write back to the source location from which a resource was loaded, as it may not exist in the filesystem at all. It may be in a jar file, for instance, and the JVM will not update the jar file.

Sign up to request clarification or add additional context in comments.

2 Comments

May you gime me an a example how to write it corectly?
You cannot write it correctly. You cannot in general write to the location from which a resource was loaded. It may not exist in a writable location.
3

May be it works

try
{
java.net.URL url = this.getClass().getResource("/resources/SQL.properties");

java.io.FileInputStream pin = new java.io.FileInputStream(url.getFile());

java.util.Properties props = new java.util.Properties();

props.load(pin);
}
catch(Exception ex)
{
ex.printStackTrace();
}

and check the below url

getResourceAsStream() vs FileInputStream

Comments

1

Please see this question: How can I save a file to the class path

And this answer https://stackoverflow.com/a/4714719/239168

In summary: you can't always trivially save back a file your read from the classpath (e.g. a file in a jar)

However if it was indeed just a file on the classpath, the above answer has a nice approach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.