I have a string with multiple lines and I want to read a specific line and save it to an other string. That's my code
String text ="example text line\n
example text line\n
example text line\n
example text line\n
example text line\n
example text line\n
example text line\n";
String textline1="";
String textline2="";
on the above strings textline1 and textline2 I want to save the specific line.
You can split on the new-line character:
//To split on the new line
String[] lines = s.split("\\n");
//To read 1st line
String line1 = lines[0];
System.out.println(line1);
//To read 2nd line
String line2 = lines[1];
System.out.println(line2);
Using java.io.LineNumberReader
may also be useful here, as it handles the various types of line endings that may be encountered. From its API doc :
A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed.
Example code:
package com.dovetail.routing.components.camel.beans;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import org.testng.annotations.Test;
@Test
public final class SoTest {
private String text = "example text line 1\nexample text line 2\nexample text line\nexample text line\nexample text line\nexample text line\nexample text line\n";
String textline1 = "";
String textline2 = "";
public void testLineExtract() throws IOException {
LineNumberReader reader = new LineNumberReader(new StringReader(text));
String currentLine = null;
String textLine1 = null;
String textLine2 = null;
while ((currentLine = reader.readLine()) != null) {
if (reader.getLineNumber() == 1) {
textLine1 = currentLine;
}
if (reader.getLineNumber() == 2) {
textLine2 = currentLine;
}
}
assertThat(textLine1).isEqualTo("example text line 1");
assertThat(textLine2).isEqualTo("example text line 2");
}
}
I would use Guava 's Splitter
to turn text
into an Iterable<String>
(call it, say, lines
). Then it's just a matter of getting your element via Iterables.get(lines, 1)
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.