JAVA: FileInputStream and FileOutputStream
Asked Answered
C

3

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

Clavicembalo answered 8/5, 2012 at 4:48 Comment(1)
Welcome to SO. +1 for a well-phrased question with all the appropriate information.Roundtheclock
F
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

Fluoroscopy answered 8/5, 2012 at 5:4 Comment(0)
R
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.

Roundtheclock answered 8/5, 2012 at 4:51 Comment(2)
May you gime me an a example how to write it corectly?Clavicembalo
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.Roundtheclock
F
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

Fluoroscopy answered 8/5, 2012 at 5:4 Comment(0)
T
1

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

And this answer https://mcmap.net/q/685915/-how-can-i-save-a-file-to-the-class-path-closed

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

Tracey answered 8/5, 2012 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.