简体   繁体   English

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

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

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. 在上面的字符串textline1和textline2我想保存特定的行。

You can split on the new-line character: 您可以拆分换行符:

//To split on the new line //在新线上拆分

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

//To read 1st line //阅读第1行

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

//To read 2nd line //阅读第2行

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. 使用java.io.LineNumberReader在这里也很有用,因为它处理可能遇到的各种类型的行结尾。 From its API doc : 从其API文档

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. 一条线被认为是由换行符('\\ n'),回车符('\\ r')或回车符中的任何一个终止,后面紧跟换行符。

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 ). 我会使用GuavaSplittertext转换为Iterable<String> (称之为lines ,称为lines )。 Then it's just a matter of getting your element via Iterables.get(lines, 1) ; 然后,这只是通过Iterables.get(lines, 1)获取元素的问题;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM