2012-02-21 313 views
2

我有一個多行的字符串,我想讀取一個特定的行並將其保存到另一個字符串。這是我的代碼如何從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我想保存特定的行。

+0

界定「特定」行 – adarshr 2012-02-21 20:21:23

+1

我希望這只是一個錯字,因爲你不能申報多串那樣。 – Jivings 2012-02-21 20:21:38

+0

你知道那裏有多少條「線路」嗎?你會只讀過第二行嗎? – 2012-02-22 15:12:29

回答

9

您可以在換行字符分割:

//拆就新的生產線

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

//讀取一號線

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

//閱讀二號線

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

它不工作....這輸出「1」,不輸出線.... – 2012-02-21 22:03:05

+0

我測試了它,它工作 – Bozho 2012-02-21 22:27:20

+0

我測試它到一個新班級,你是對的。它正在工作......有些東西與我的代碼不匹配。謝謝 – 2012-02-22 01:53:45

0

我會用GuavaSplittertext變成Iterable<String>(稱之爲lines)。那麼這只是通過Iterables.get(lines, 1)獲取元素的問題;

+0

公平起見,'Iterable'沒有'get'方法,所以你必須先將它複製到列表中。 =/ – 2012-02-21 20:23:55

+0

哎呀。或者使用Iterables.get – Ray 2012-02-22 03:12:32

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

} 
相關問題