How can I add a newline character to a String in Java? - java

In a Java application, I am creating a String like below (by concatenation):
String notaCorrente = dataOdierna + " - " + testoNotaCorrente;
My problem is that I want to add also something like an HTML newline character at the end of this String (that will be shown into an HTML page).
How can I implement it?

The newline character in Java is "\n" which will look like this:
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "\n";
However, this will not display as you expect on your HTML page. You can try adding an html break tag, or add the
(Line Feed) and 
 (Carriage Return) HTML entities:
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br>";
or
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "
&#10";

For a newline that will result in a line break in HTML, use
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br>";
For a newline that will result in a line break in your text editor, use
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + System.lineSeparator();
And for both, use
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br>" + System.lineSeparator();
Why not \n?
\n is specific to certain operating systems, while others use \r\n. System.lineSeparator() will get you the one that is relevant to the system where you are executing your application. See the documentation for more info on this function, and Wikipedia for more info on newlines in general.

Simply, need to add <br/> (break line tag of HTML).
String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br/>";
so, while you are going to display this content, <br/> tag will rendered on HTML page in form of new line.

Related

API endpoint how to return a string with new line

In my custom GET endpoint, I would like to return a String but, to "beautify" it, I would like to insert new line for each different information. I've tried with \n\r this way
return "Name of process definition: "+ obj.getString("processDefinitionName") + "\r\n" + "Start time of instance: " + obj.getString("startTime")
+ "||" + "End time of the instance: " + obj.getString("endTime") + "||" + "Total duration time(ms): " + obj.getInt("durationInMillis");
but it only prints a white space and the text is written on the same line. Why is it not working?
You have to use HTML tags to display new line on browser. You can use <br/> tag to add new line. Browser parses your response in HTML form.

How to remove specific line from multi-line string

I have below java string as command output
String output = "NIC Value\n"
+ "------ -----\n"
+ "vmn0 on \n"
+ "vmn1 on \n"
+ "vmn2 on \n"
+ "vmn3 on \n"
+ "vmn4 on";
I want to remove second line with dash from above string. How can I do it?
I tried it using contains method but it is generating blank line after removing second line.
if(output!=null && output.contains("-"))
output = output.replace("-","");
This is complete answer you are looking for:
String output = "NIC Value\n"
+ "------ -----\n"
+ "vmn0 on \n"
+ "vmn1 on \n"
+ "vmn2 on \n"
+ "vmn3 on \n"
+ "vmn4 on";
String str = Stream.of(output.split("\n"))
.filter(s -> !s.contains("--"))
.collect(Collectors.joining("\n"));
You can use this to remove that line and use the result,
String result = output.replace("------ -----\n", "");
It will replace that line with an empty String

How to replace all domains with pattern in a XML string in Java?

I have an XML output like this (<xml> element or xlink:href attribute are just fiction and you cannot rely on them to create regex pattern.)
<xml>http://localhost:8080/def/abc/xyx</xml>
<element xlink:href="http://localhostABCDEF/def/ABC/XYZ">Some Text</element>
...
What I want to do is using Java regex to replace the domain pattern (I don't know about existing domains):
"http(s)?://.*/def/.*
with an input domain (e.g: http://google.com/def) and the result will be:
<xml>http://google.com/def/abc/xyx</xml>
<element xlink:href="http://google.com.com/def/ABC/XYZ">Some Text</element>
...
How can I do it? I think Regex in Java can do or String.replaceAll (but this one seems not possible).
Regex: http[s]?:\/{2}.+\/def Substitution: http://google.com/def
Details:
? Matches between zero and one times
[] Match a single character present in the list
. Matches any character
+ Matches between one and unlimited times
Java code:
String domain = "http://google.com/def";
String html = "<xml>http://localhost:8080/def/abc/xyx</xml>\r\n<element xlink:href=\"http://localhostABCDEF/def/ABC/XYZ\">Some Text</element>";
html = html.replaceAll("http[s]?:\\/{2}.+\\/def", domain);
System.out.print(html);
Output:
<xml>http://google.com/def/abc/xyx</xml>
<element xlink:href="http://google.com/def/ABC/XYZ">Some Text</element>
Actually, this could be done with Regex and it is simple enough than parsing XML document. Here is the answer:
String text = "<epsg:CommonMetaData>\n"
+ " <epsg:type>geographic 2D</epsg:type>\n"
+ " <epsg:informationSource>EPSG. See 3D CRS for original information source.</epsg:informationSource>\n"
+ " <epsg:revisionDate>2007-08-27</epsg:revisionDate>\n"
+ " <epsg:changes>\n"
+ " <epsg:changeID xlink:href=\"http://www.opengis.net/def/change-request/EPSG/0/2002.151\"/>\n"
+ " <epsg:changeID xlink:href=\"http://www.opengis.net/def/change-request/EPSG/0/2003.370\"/>\n"
+ " <epsg:changeID xlink:href=\"http://www.opengis.net/def/change-request/EPSG/0/2006.810\"/>\n"
+ " <epsg:changeID xlink:href=\"http://www.opengis.net/def/change-request/EPSG/0/2007.079\"/>\n"
+ " </epsg:changes>\n"
+ " <epsg:show>true</epsg:show>\n"
+ " <epsg:isDeprecated>false</epsg:isDeprecated>\n"
+ " </epsg:CommonMetaData>\n"
+ " </gml:metaDataProperty>\n"
+ " <gml:metaDataProperty>\n"
+ " <epsg:CRSMetaData>\n"
+ " <epsg:projectionConversion xlink:href=\"http://www.opengis.net/def/coordinateOperation/EPSG/0/15593\"/>\n"
+ " <epsg:sourceGeographicCRS xlink:href=\"http://www.opengis.net/def/crs/EPSG/0/4979\"/>\n"
+ " </epsg:CRSMetaData>\n"
+ " </gml:metaDataProperty>"
+ "<gml:identifier codeSpace=\"OGP\">http://www.opengis.net/def/area/EPSG/0/1262</gml:identifier>";
String patternString1 = "(http(s)?://.*/def/.*)";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
String prefixDomain = "http://localhost:8080/def";
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String url = prefixDomain + matcher.group(1).split("def")[1];
matcher.appendReplacement(sb, url);
System.out.println(url);
}
matcher.appendTail(sb);
System.out.println(sb.toString());
which returns output https://www.diffchecker.com/CyJ8fY8p

How can I split the data over multiple lines in a JTextArea?

How can I put each line of the host in the message body? I work with a JTextArea.
String host = InetAddress.getLocalHost().getHostName().toString();
texto_recepcion.setText(host + texto_recepcion.getText() + dpRecepcion.getAddress() + " " + mensaje_recibido + "\n");
How it is now:
I resolve my question with append function.
String host = InetAddress.getLocalHost().getHostName().toString();
texto_recepcion.append(host); // ***Use the function append for solve the problem***
texto_recepcion.setText(texto_recepcion.getText() + dpRecepcion.getAddress() + " " + mensaje_recibido + "\n");
Thanks a lot
Why don't you add the newline character "\n" to the beginning of the string?
texto_recepcion.setText("\n" + host + texto_recepcion.getText() + dpRecepcion.getAddress() + " " + mensaje_recibido);

Aligning a String in JOptionPane

I have a string that I want to display in a JOptionPane.
String info = "Name:" + _name + "\n" +
"Phone:" + _phone;
I tried to add \t but it didn't work.
I tried also to
int choose = JOptionPane.showConfirmDialog(this,new JTextArea(info),"XXX",0);
But it doesn't look good.
Are there another ways to do that? (If you know about a solution where I can use something like \t it will be very usefull for me)
* In this specific example I can manually align it, but I'm looking for a general solution.
HTML formatting could help:
String info = "Name:" + _name + "<br>" +
"Phone:" + _phone + "<br>";
int choose =
JOptionPane.showConfirmDialog(this, "<html>" + info + "</html>", "XXX", 0);
Another option is to use a JTable in the JOptionPane dialog as shown in this solution.
I had something like that and it worked:
String st = "<table border = \"0\">" +
"<tr><td>VALUE1: </td><td>" + _value2 + "</td></tr>"+
"<tr><td>VALUE2: </td><td>" + _value4 + "</td></tr>" +
//.....
"</table>";

Categories