2016-11-26 82 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

我可以建议你继续使用一个真实采集结构之后