Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 303
gedO Avatar asked May 08 '12 04:05

gedO


People also ask

What is FileInputStream and FileOutputStream in Java?

There are two types of streams available − InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination.

What is difference between FileInputStream and FileReader in Java?

FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files. FileReader is used for reading text files in platform default encoding.

Which package have FileInputStream and FileOutputStream classes?

The FileInputStream class of the java.io package can be used to read data (in bytes) from files. It extends the InputStream abstract class.

What is Java FileInputStream?

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .


2 Answers

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.

like image 61
Jim Garrison Avatar answered Oct 17 '22 22:10

Jim Garrison


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

like image 45
user1357722 Avatar answered Oct 17 '22 21:10

user1357722