how to read an ArrayList from a text file in Java?
Solution 1
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.
Solution 2
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);
}
}
Solution 3
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:
- You i2 loop should be for (i2 = 0; i2 < theword.length; i2 += 2) {
- I wouldn't set the initial size of the ArrayList unless you know how many items are in the file.
- Are there two spaces between your username and password?
- Have you looked into serialization?
Why not have a new line for each username and password It would be a lot easier to load.
username1
password1
username2
password2
Lox
Updated on June 21, 2022Comments
-
Lox almost 2 years
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"); }