baba ramdev baba ramdev - 14 days ago 10
Java Question

Repeating string inside loop

I'm trying to read a

contact name
,
email
and
mobile number
from file(i.e contact.txt) using split function. So i captured all those strings into array using
\n
and
"<space>"
.

Inside my file
contact.txt
, data is followed as below:

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


Here is my code looks like:

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


Now it started giving the output same string with repeating loop wise, Output as followed:

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1

name1
email1
mobile_1


Please let me know, How to retrieve my all data series wise?

Help would be appreciated, Thanks in advanced!

Answer

Try this after the try block

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