如何从Java中的文本文件中读取ArrayList?

时间:2010-05-09 21:09:48

标签: java file-io arraylist

ArrayList的单个条目的格式为:

public class Account {
    String username;
    String password;
}

我设法在文本文件中添加了一些“帐户”,但现在我不知道如何阅读它们。 这就是我的ArrayList在文本文件中的显示方式:

username1 password1 | username2 password2 | etc

这是我提出的代码的一部分,但它不起作用。

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

3 个答案:

答案 0 :(得分:3)

更强大的解决方案是定义与该行匹配的正则表达式,并使用Matcher.group(...)调用来拉出字段。例如,

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 ...

在处理格式问题时,这也更加强大。所有这一切都寻找成对的单词。它不关心用什么字符串来分隔它们或者它们之间有多少空格。

我猜对了正则表达式。根据输入的确切格式,您可能需要稍微调整一下。

答案 1 :(得分:2)

你的问题不清楚是什么问题。但是,我希望您在包含循环中处理“”(theword)上的拆分结果,而不是在外部处理它。

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

答案 2 :(得分:1)

它做错了什么?你有没有使用调试器?如果是这样,哪一部分引起了这个问题呢?

我注意到的事情:

  1. 你的i2循环应该是(i2 = 0; i2&lt; theword.length; i2 + = 2 ){
  2. 除非您知道文件中有多少项,否则我不会设置ArrayList的初始大小。
  3. 您的用户名和密码之间是否有两个空格?
  4. 您是否考虑过序列化?
  5. 为什么不为每个用户名和密码设置一个新行。加载它会容易得多。

    USERNAME1
     密码1
     USERNAME2
     password2

相关问题