2016-11-26 139 views
-2

我正在嘗試使用分割函數從文件(即contact.txt)讀取contact nameemailmobile number。所以我使用\n"<space>"將所有這些字符串捕獲到數組中。在循環內重複字符串

在我的文件contact.txt,數據如下如下:

name1 email1 mobile_1 
name2 email2 mobile_2 
name3 email3 mobile_3 
name4 email4 mobile_4 
name5 email5 mobile_5 
name6 email6 mobile_6 

這裏是我的代碼如下所示:

String usersInfo; 

BufferedReader br = new BufferedReader(new FileReader("C:/contact.txt")); 
try { 
    StringBuilder sb = new StringBuilder(); 
    String line = br.readLine(); 

    while (line != null) { 
     sb.append(line); 
     sb.append(System.lineSeparator()); 
     line = br.readLine(); 
    } 
    usersInfo = sb.toString(); 
} finally { 
    br.close(); 
} 


String[] splitStrNewLine = usersInfo.split("\n"); 
String[] splitStrSpace = usersInfo.split("[ \n]"); 


for(int i=0; i<=5; i++){ 
    for(int j=0; j<=2; j++){ 
     System.out.println(splitStrSpace[j]); 
    } 
} 

現在開始給帶有重複循環明智的,輸出的輸出相同的字符串如下:

name1 
email1 
mobile_1 

name1 
email1 
mobile_1 

name1 
email1 
mobile_1 

name1 
email1 
mobile_1 

name1 
email1 
mobile_1 

name1 
email1 
mobile_1 

請讓我知道,如何找回我的所有數據系列明智?

幫助將不勝感激,提前致謝! try塊

String[] splitStrNewLine = usersInfo.split("\n"); 

fileLength = splitStrNewLine.length(); 

for(int i=0; i<fileLength; i++){ 
    splitStrSpace = splitStrNewLine[i].split("[ ]"); \\specify delimiter you want to split 
    for(int j=0; j<splitStrSpace.length(); j++){ 
     System.out.println(splitStrSpace[j]); 
    } 
} 
+0

底部的循環似乎並沒有使用'i'索引 – Nicko

+0

在那種情況下我應該使用什麼? –

+0

爲什麼不直接在while循環中分割聯繫人信息? –

回答

0

試試這個?您正在使用readLine來獲取線條。爲什麼將它們粘貼在一起插入一個字符,然後再次解析出來? 。

List<String> usersInfo = new ArrayList<String>() 
BufferedReader br = new BufferedReader(new FileReader("C:/contact.txt")); 
try { 
    String line = br.readLine(); 
    while (line != null) { 
     lines.add(line); 
     line = br.readLine(); 
    } 
} finally { 
    br.close(); 
} 

現在你有一個結構,很容易重複,你會得到每行回來一樣,它排在現在,只需重複線路,並分割每行需要:

for(String line : userInfo){ 
    String[] splitStrSpace = line.split("[ ]"); 
    for(int j=0; j<=splitStrSpace.length; j++){ 
     System.out.println(splitStrSpace[j]); 
    } 
} 
+0

謝謝...... ...... :) –

0

我可以建議你繼續使用一個真實採集結構之後