Here's the code:
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("src/prop.txt");
//Read the content
byte[] bys = new byte[1024];
int len;
while((len=fis.read(bys))!=-1) {
System.out.println(new String(bys));
}
//Load the properties and print
prop.load(fis);
fis.close();
System.out.println(prop);
The src/prop.txt is simple as:
city=LA
country=USA
It prints out nothing in the prop, meaning the prop is empty:
{}
But if I remove the part of reading, prop can be loaded as:
{country=USA, city=LA}
Why is it failed to fulfill the prop after reading the content of prop.txt?
CodePudding user response:
After you read the stream, the stream pointer points to the end of the stream. After that when prop.load()
try to read from the stream, nothing more is available. You have to call reset()
on the stream before reading it again.
Properties prop = new Properties();
BufferedInputStream fis = new BufferedInputStream(new FileInputStream("src/prop.txt"));
fis.mark(fis.available()) //set marker at the begining
//Read the content
byte[] bys = new byte[1024];
int len;
while((len=fis.read(bys))!=-1) {
System.out.println(new String(bys));
}
fis.reset(); //reset the stream pointer to the begining
//Load the properties and print
prop.load(fis);
fis.close();
System.out.println(prop);
CodePudding user response:
It prints out nothing in the prop, meaning the prop is empty:
Because you have already gone through the data available in your input stream fis
, by fis.read(bys)
in your while
condition (see what actually read(byte[] b)
does), and there is nothing left when you're loading it into your properties.
FileInputStream
is not a type that holds the data persistently; it's rather an object, that represents a pipe, a connection to the file descriptor, and data flows from the file, byte by byte, as long as you keep calling .read(..)
on it.
Also, read Oracle docs:
FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader
CodePudding user response:
Better use ResourceBundle for loading the properties file. Assuming that you are using maven, you can place the properties file name application.properties in the folder "src/main/resources" and you load and using below code:
ResourceBundle resourceBundle = ResourceBundle.getBundle("application");
String value = resourceBundle.getString("key");
Please refer to the javadocs of ResourceBundle for more details.
More examples at https://mkyong.com/java/java-resourcebundle-example/ or https://www.baeldung.com/java-resourcebundle
CodePudding user response:
You are printing bys, which is byte
array. You should print len
instead
System.out.println(len)