簡體   English   中英

如何從java中的字符串中讀取第二行

[英]How to read second line from a string in java

我有一個包含多行的字符串,我想讀取一個特定的行並將其保存到另一個字符串。 那是我的代碼

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

//閱讀第1行

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

//閱讀第2行

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

使用java.io.LineNumberReader在這里也很有用,因為它處理可能遇到的各種類型的行結尾。 從其API文檔

一條線被認為是由換行符('\\ 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");
    }

}

我會使用GuavaSplittertext轉換為Iterable<String> (稱之為lines ,稱為lines )。 然后,這只是通過Iterables.get(lines, 1)獲取元素的問題;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM