繁体   English   中英

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

[英]how to read an ArrayList from a text file in Java?

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

一个更可靠的解决方案是定义一个与行匹配的正则表达式,并使用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 ...

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

我只是在正则表达式上猜到了。 您可能需要根据输入的确切格式对其进行调整。

目前尚不清楚您的问题出了什么问题。 但是,我希望您处理在包含循环内对“”( 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);
               }  
          }

它做错了什么? 您是否已调试过调试器? 如果是这样,那是造成该问题的原因?

我注意到的事情:

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

    USERNAME1
    密码1
    USERNAME2
    密码2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM