Reputation: 1723
I have a text file like this:
fname, lname~email~info
fname, lname~email~info
fname, lname~email~info
fname, lname~~info
I need to split these strings into either a 1 or 2D array. I have used this code:
public void readFile() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("contacts.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
// store data into array
for (String retval: everything.split("~")){
System.out.println(retval);
}
// store data into array
//String[] retval = everything.split("~");
//System.out.println(retval[2]);
} finally {
br.close();
}
}
But the problem is the reader doesn't split the new lines, it ended up giving me this as a string
info
fname, lname
as a string (yes with the spaces)
How would I achieve this within one step of split? And note that the last line of text file doesn't have the email part, hence the the split should store an empty string, not skipping it.
THanks
Upvotes: 1
Views: 109
Reputation: 6816
You can change it to
everything.split("~|[\r\n]+");
for (String retval: everything.split("~")){
if(retval !=null && !retail.isEmpty) {
System.out.println(retval);
} else {
System.out.Println("String is empty or null");
}
}
Upvotes: 1
Reputation: 70732
I would say you are looking to split on ~
and newline sequences. The following should work for you.
everything.split("~|[\r\n]+");
Upvotes: 1