问题
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???
回答1:
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
回答2:
try this
String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);
回答3:
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..
回答4:
If you are retrieving your data to a HTML page, you can do the following:
String YourString = YourString.replaceAll("\\n", "<br>");
If you are retrieving your data to something else, you can do this:
String YourString = YourString.replaceAll("\\n", "\n");
来源:https://stackoverflow.com/questions/15678768/java-is-not-treating-n-as-new-line-when-retrieved-from-database-column