Do anyone know if it is possible to have lower case letters in a property file in Java?
Currently when I have Example:
My_Conf=1234567
I get, when checking the property
My_Conf=null
in the code.
The code is suppose to be ran in Jboss servlet engine.
Best regards
Yes, it is definitely possible to have lower case characters in a .properties file. The problem might be that your code doesn't load the file.
For more information, have a look here: http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#load%28java.io.Reader%29
Try this for debugging purpose:
String filename = "example.properties";
Properties properties = new Properties();
BufferedInputStream stream = null;
try {
stream = new BufferedInputStream(new FileInputStream(filename));
try {
properties.load(stream);
String prop = properties.getProperty("My_Conf");
System.out.println(prop);
} catch (IOException e) {
System.out.println("IOException");
}finally{
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
Related
Here's what I need to happen: I've got a text file with some values in them that I need to read (Let's say it is example.txt). I need to read that file like i would using ex. FileInputStream or BufferedReader). How would I go about doing it?
PS - This is what I tried doing, but it didn't help. I would always get an error saying the file has to be .xml
try {
BufferedReader bufferReader = new BufferedReader(new FileReader(file);
try {
String line = bufferReader.readLine();
while(line != null) {
//do something
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I am trying to convert English words from a text file to a new file that translates the words into pig Latin. Everything translates the way it should when it is simply printed to the console but the issue I am having is that only the last line from the initial file appears on the new one.
public static void newFile(String pigLatin) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("/Users/amie/Documents/inputnewnew.pig.txt"));
os.write(pigLatin.getBytes(), 0, pigLatin.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By default FileOutputStream is overriding the existing file. What you need to do is to use another constructor with append parameter
FileOutputStream(String name, boolean append)
like
os = new FileOutputStream(new File("/Users/...", true))
Take a look at the reference
I have a property file like this:
[flags]
prop1=value
prop2=value
[patterns]
prop3=#.00
prop4=###,##0.00
[other]
prop5=value
When I process the file, not only the pound signs are escaped (#), but all my properties are out of order.
my code is something like this:
Properties props = new Properties();
FileInputStream in = null;
try
{
in = new FileInputStream(PROP_FILE);
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
props.load(reader);
}
catch (IOException e)
{
// log exception
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
// log exception
}
}
}
props.setProperty("prop5", "otherValue");
try
{
OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(INI_FILE), StandardCharsets.UTF_8);
props.store(w, null);
}
catch (IOException e)
{
// log exception
}
I am using props.store() because I do not know of another way to save the properties file after props.setProperty() is called.
All the credit goes to Jon Skeet for pointing out that Java Properties are not meant to be used this way, and that what I needed was a Windows-style .ini file. Because of this suggestion, I remember I used ini4j many years ago and that is what I needed to use in this case.
The solution is quite simple:
try
{
Wini ini = new Wini(new File(PROP_FILE));
ini.put("others", "prop5", value); // "others" is the section, "prop5" the key, and "value" is self-explanatory.
ini.store(); // INI file is saved
}
catch (IOException e)
{
// log problem... do whatever!
}
When using ini4j to save, my properties are preserved in sections, and the order of properties is preserved, and special characters (like #) are not escaped; which addresses ALL of the issues.
I created a new file roomChecker which is empty. Now when I read it, it throws me an EOFException which is undesirable. Instead I want it to see that, if file is empty then it would run other two functions that are in if(roomFeed.size() == 0) condition. I could write this statement in EOFException catch clause; but that's not what I want to do because then every time when the file will be read and reaches end of file it will execute those functions. Instead when the file has some data it should do what is specified in else.
File fileChecker = new File("roomChecker.ser");
if(!fileChecker.exists()) {
try {
fileChecker.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to create new File");
}
}
try(FileInputStream fis = new FileInputStream("roomChecker.ser"); ObjectInputStream ois = new ObjectInputStream(fis)) {
roomFeed = (List<roomChecker>) ois.readObject();
System.out.println("End of read");
if(roomFeed.size() == 0) {
System.out.println("your in null if statement");
defaultRoomList();
uploadAvailableRooms();
} else {
for(int i=0; i<roomNumber.size(); i++) {
for(int j=0; j<roomFeed.size(); i++) {
if((roomNumber.get(i)).equals(roomFeed.get(i).getRoomNumSearch())){
System.out.println("Reach Dead End for now");
} else {
defaultRoomList();
uploadAvailableRooms();
}
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
All this:
if(!fileChecker.exists()) {
try {
fileChecker.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to create new File");
}
}
is a complete waste of time, and it is one of two possible causes for your empty file problem. Creating a file just so you can open it and then get a different problem instead of coping correctly with the original problem of the file not being there isn't a rational strategy. Instead, you should do this:
if (fileChecker.isFile() && fileChecker.length() == 0) {
// file is zero length: bail out
}
and, in the following code, this:
try(FileInputStream fis = new FileInputStream(fileChecker); ObjectInputStream ois = new ObjectInputStream(fis)) {
// ...
}
catch (FileNotFoundException exc) {
// no such file ...
}
// other catch blocks as before.
Of course you can still get EOFException if you read the file to its end, or if the file is incomplete, and you still need to handle that.
Which would be considered more proper technique for implementing a try/catch in Java:
A:
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
try {
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (IOException e) {
e.printStackTrace();
}
} catch(FileNotFoundException e) {
e.printStackTrace();
}
or B:
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Also, is it wrong to follow the try/catch block with a long block of code that makes use of the BufferedReader, or is it preferred to include the long block of code inside the try/catch?
For example:
public static void main(String[] args) {
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Long block of code using inFile
inFile.readLine();
inFile.close();
Versus:
public static void main(String[] args) {
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
lastMod = new Date(Long.parseLong(inFile.readLine()));
//Long block of code using inFile
inFile.readLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
inFile.close();
}
B is much more readable, when there is nothing going on after the internal try block, before the external try block. If you have logic to perform in between, then you must use A
In the second example the second version using finally is critical to ensure that close will be called no matter what (even if the function returns first) The first version without finally is actually wrong, since you may use up all the file handles and be unable to open more files.
As an additional note, you may need to check for null when calling close. And if you are using java 7, it's even better to use "try with resources".
For the first question: the solution A add unnecessary complexity. Use B or, if you are using Java 7, try-with-resources:
Date lastMod = null;
try (BufferedReader inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"))){
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (FileNotFoundException | IOException e) {
e.printStackTrace();
}
For the second question: in the first version, what if the BufferedReader creation throws an exception? You would use brafter which is null and would throw a NullPointerException. Also if something else happen, you will not have called inFile.close(), so you really need a finally. For all these reasons, again, the second solution is better.
If you are using try-with-resouces (Java 7), of course, you don't need a finally block to release your BufferedReader.
Proper technique might also include not catching your exceptions, but allowing them to bubble up to a caller instead. Do always use a finally block to clean up any state that might otherwise use up resources, but you'll often be better off catching the exception in the parent routine rather than the child routine in which the exception was thrown.
In general, if it would be helpful to know in the calling routine whether the sub-routine succeeded or not, then that sub-routine should not catch its exceptions, but should allow them to bubble up to their caller.