Reputation: 1733
I'm writing a simple parser to convert a java properties file which contains entries in name=value
pair to a json
string.
Below is the code. The code requires that each entry is in a new line:
sCurrentLine = br.readLine();
while ((sCurrentLine) != null)
{
config+=sCurrentLine.replace('=', ':');
sCurrentLine = br.readLine()
if(sCurrentLine!=null)
config+=",";
}
config+="}";
The function works fine except in cases when there are extra empty new lines in the properties file. (Ex: Suppose I write the last entry in the props file and then hit two enters, the file will contain two empty new lines after the last entry) . While the expected output is {name1:value1,name2:value2}
, in the above case when extra new lines are present , I get the output as {name1:value1,name2:value2,}
. The number of trailing ,
increases with the number of empty new lines.
I know its because the readLine()
reads the empty line while logically it shouldn't but how do I change this?
Upvotes: 1
Views: 12648
Reputation: 576
The following code will check regex for empty line . this should also do
if (sCurrentLine != null){
if (!sCurrentLine.matches("^\\s*$")) // matches empty lines
config += ",";
}
Upvotes: 1
Reputation: 27346
This could be solved using the contains()
method. Simply ensure the existence of a "="
in your line..
while ((sCurrentLine) != null)
{
if(sCurrentLine.contains("=") {
config+=sCurrentLine.replace('=', ':');
sCurrentLine = br.readLine()
if(sCurrentLine!=null)
config+=",";
}
}
Example
sCurrentLine = "name=dave"
if(sCurrentLine.contains("=")) // Evaluates to true.
// Do logic.
sCurrentLine = ""
if(sCurrentLine.contains("=")) // Evaluates to false.
// Don't do logic.
sCurrentLine = "\n"
if(sCurrentLine.contains("=")) // Evaluates to false.
// Don't do logic.
I know its because the readLine() reads the empty line while logically it shouldn't but how do I change this?
readLine()
reads everything up to \n
. That's how it can check for a new line. You've got \n
and nothing before it, so your line will consist of ""
because \n
is omitted.
Slight enhancement
If you want to make sure your line definitely has a name and a property in it, then you can use some simple regex.
if(s.CurrentLine.matches("\\w+=\\w+"))
// Evaluates to any letter, 1 or moe times, followd by an "=", followed by letters.
Upvotes: 2
Reputation: 3948
One way is the use of method trim()
to check is the current line empty or not:
sCurrentLine = br.readLine();
while ((sCurrentLine) != null)
{
If ("".equals(sCurrentLine.trim()) == false)
{
config+=sCurrentLine.replace('=', ':');
sCurrentLine = br.readLine()
if(sCurrentLine!=null)
config+=",";
}
}
config+="}";
Upvotes: 1