2012-02-21 6 views
2

複数行の文字列があり、特定の行を読み込んで別の文字列に保存したい。それは私のコードですJavaの文字列から2行目を読み取る方法

上記の文字列textline1とtextline2特定の行を保存します。

+0

は、あなたがそのような複数行の文字列を宣言することはできませんので、私はそれがちょうど誤植願っています – adarshr

+1

「特定」の行を定義します。 – Jivings

+0

あらかじめ何本の「線」があるのをご存知ですか?第二の行だけを読むことはできますか? –

答えて

9

あなたは、改行文字で分割することができます

//読み取るには1行目

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

//を読むには、新しい行に

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

//を分割します2行目

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

それは動作していません....これは "1"を出力し、出力しません.... –

+0

私はそれをテストし、それは働いた – Bozho

+0

私は新しいクラスにテストし、あなたは正しいです。それは働いています...私のコードと一致しないものがあります。ありがとうございます –

0

GuavaSplittertextに変更してIterable<String>にします(例:lines)。それでは、要素を得ることは問題ありません。Iterables.get(lines, 1);

+0

公正であるためには、 'Iterable'メソッドは' get'メソッドを持たないので、リストに最初にコピーする必要があります。 =/ –

+0

または、Iterables.getを使用します。 – Ray

0

java.io.LineNumberReaderを使用すると、遭遇する可能性のあるさまざまなタイプの行末を処理するので、ここでも便利です。そのAPI docから:ラインがラインフィード(「\ 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"); 
    } 

} 
関連する問題