如何在java中读取字符串的第二行
我有一个包含多行的字符串,我想读取一个特定的行并将其保存到另一个字符串中。这是我的密码如何在java中读取字符串的第二行,java,parsing,line,Java,Parsing,Line,我有一个包含多行的字符串,我想读取一个特定的行并将其保存到另一个字符串中。这是我的密码 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=""; 在上面的字符
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="";
在上面的字符串textline1和textline2上,我想保存特定的行。您可以在新行上拆分字符: //在新行上拆分
String[] lines = s.split("\\n");
//读第一行
String line1 = lines[0];
System.out.println(line1);
//读第二行
String line2 = lines[1];
System.out.println(line2);
我会使用的
拆分器
将文本
转换为Iterable
(比如说,将其称为行
)。然后,只需通过Iterables获取元素即可。get(line,1)
使用java.io.LineNumberReader
在这里可能也很有用,因为它可以处理可能遇到的各种类型的行尾。从其:
一行被认为是由换行符('\n')、回车符('\r')或紧接着换行符的回车符中的任意一个终止的
示例代码:
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");
}
}
我希望这只是一个输入错误,因为你不能像那样声明多行字符串。你提前知道有多少行吗?你会只读第二行吗?公平地说,
Iterable
没有get
方法,所以你必须先把它复制到列表中=/我在一门新课上测试了它,你是对的。它正在工作…与我的代码不匹配。谢谢如果您只需要字符串的第二行,请不要忘记使用方法split的limit参数<代码>s.split(\\n“,2)代码>