I am facing a weird problem.
What I am doing is I am storing some values in DB(oracle 11g) as varchar2 and fetching the values in java and working with the fetched data.
Now I have \n as a value in DB and getting it in java using rs.getString()
. I am getting proper value \n
.
String newLine=rs.getString("column_value");
Now i parse a HTML page and get the whole page as a string.Suppose the page has 3 lines each depiciting ssome informations like below:
Time: 08 AM - 11 AM
Duration : 36 minutes
Now in code i will pass "Duration :" to a method and that will return me "36 minutes".
What logic i use is i get the index of "Duration :" and read till "\n" is encountered.Code works fine if i declare the newline as
String newLine= "\n";
But if i get it from DB it does not work. I know i don't need to store this in DB but i don't want to hardcode these items. So i have to store it in DB only. Can anyone help me out in this???
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
“\n” is an Escape Character in Java that is used to enter a new line in the output. It is also known as the end of line or line break. It is a platform-dependent line separator, mostly used to break a line because of its easy syntax. It helps the programmers to increase the readability of code.
\b - backspace (a step backward in the text or deletion of a single character). \n - new line. \r - carriage return.
'\n' itself is one character when represented internally in Java, but when interfacing with external systems it can be represented by anywhere between 1 and 8 bytes.
The problem is that the database is adding a escape character to your string, so you end up with \\n instead of \n. To fix this you could just replace \\n with \n.
String db_string = new String("This is a string from the db \\n This should be a new line, but is not.");
db_string = db_string.replace("\\n", "\n");
If you print this you get:
This is a string from the db
This should be a new line, but is not. //well it is now..
If when you print the newLine
you get \n
in the output, you might have to unescape the string you get from the DB. The Apache Commons Lang have a method for that:
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#unescapeJava(java.io.Writer, java.lang.String)
So you would have simply to call
String newLine = StringEscapeUtils.unescapeJava(rs.getString("column_value"));
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With