简体   繁体   中英

JAVA: FileInputStream and FileOutputStream

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

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.

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

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 (eg a file in a jar)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM