Reputation: 299
The single entry of my ArrayList
is of the form:
public class Account {
String username;
String password;
}
I managed to put some "Accounts" in the a text file, but now I don't know how to read them.
This is how my ArrayList
looks in the text file:
username1 password1 | username2 password2 | etc
This is a part of the code I came up with, but it doesn't work.
public static void RdAc(String args[]) {
ArrayList<Account> peoplelist = new ArrayList<Account>(50);
int i,i2,i3;
String[] theword = null;
try {
FileReader fr = new FileReader("myfile.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
String[] theline = line.split(" | ");
for (i = 0; i < theline.length; i++) {
theword = theline[i].split(" ");
}
for(i3=0;i3<theline.length;i3++) {
Account people = new Account();
for (i2 = 0; i2 < theword.length; i2++) {
people.username = theword[i2];
people.password = theword[i2+1];
peoplelist.add(people);
}
}
}
}
catch (IOException ex) {
System.out.println("Could not read from file");
}
Upvotes: 2
Views: 10571
Reputation: 145
a more robust solution would be to define a regular expression that matches the line and use the Matcher.group(...) call to pull out the fields. for example,
String s =
Pattern p = Pattern.compile("\\s*(\\w+)\\s+(\\w+)\\s+");
String line;
while ((line = br.readLine()) != null) {
Matcher m = p.match(line);
while (m.find()) {
String uname = m.group(1);
String pw = m.group(2);
... etc ...
this is also a lot more robust when it comes to dealing with format problems. all it does it look for pairs of words. it doesn't care what string is used to separate them or how many spaces there are in between.
i just guessed at the regex. you will probably need to tune it a bit depending on the exact format of the input.
Upvotes: 3
Reputation: 6138
What does it do wrong? Have you stepped through with a debugger? If so, which part is causuing the issue?
Things that I've noticed:
Why not have a new line for each username and password It would be a lot easier to load.
username1
password1
username2
password2
Upvotes: 1
Reputation: 272207
It's not clear what's wrong from your question. However, I'd expect you to process the results of splitting on " " (theword
) within the containing loop, rather than processing it outside.
for (i = 0; i < theline.length; i++) {
theword = theline[i].split(" ");
Account people = new Account();
for (i2 = 0; i2 < theword.length; i2++) {
people.username = theword[i2];
people.password = theword[i2+1];
peoplelist.add(people);
}
}
Upvotes: 2