JAVA: FileInputStream and FileOutputStream

I have this weird thing with input and output streams that I just can't understand. I use inputstream to read property files from these resources:

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

It finds my file and its redness successfully. I am trying to write modified settings as follows:

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

And I get a strange error while storing:

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

So why is the property path changing? How to fix it? I am using Netbeans on Windows

+6
source share
3 answers

Maybe 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 url below

getResourceAsStream () vs FileInputStream

+3
source

The problem is that getResourceAsStream() resolves the path you pass in relation to the class path, and new FileOutputStream() creates the file directly on the file system. They have different starting points for the path.

In general, you cannot write back to the original location from which the resource was downloaded, since it cannot exist at all in the file system. For example, it may be in a jar file, and the JVM will not update the jar file.

+6
source

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

And this answer is fooobar.com/questions/469488 / ...

In short: you cannot always trivially save a file that you read from the class path (for example, a file in the bank)

However, if it was really a file in the classpath, then the above answer has a nice approach

+1
source

Source: https://habr.com/ru/post/915154/


All Articles