如何从java中的字符串中读取第二行

时间:2012-02-21 20:19:52

标签: 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="";

在上面的字符串textline1和textline2上我想保存特定的行。

3 个答案:

答案 0 :(得分:9)

您可以拆分换行符:

//拆分新行

String[] lines = s.split("\\n");

//阅读第1行

String line1 = lines[0];
System.out.println(line1);

//阅读第二行

String line2 = lines[1];
System.out.println(line2);

答案 1 :(得分:0)

我会使用GuavaSplittertext变为Iterable<String>(称之为lines)。然后,这只是通过Iterables.get(lines, 1);

获取元素的问题

答案 2 :(得分:0)

使用java.io.LineNumberReader在这里也很有用,因为它处理可能遇到的各种类型的行结尾。来自API doc

  

一条线被视为由换行(&#39; \ n&#39;),回车(&#39; \ r&#39;)或回车后的任何一个终止通过换行。

示例代码:

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");
    }

}
相关问题