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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2799189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:53:52  来源:igfitidea点击:

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

javafile-ioarraylist

提问by Lox

The single entry of my ArrayListis of the form:

my 的单个条目ArrayList的形式为:

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 ArrayListlooks in the text file:

我设法将一些“帐户”放入文本文件中,但现在我不知道如何阅读它们。这是我ArrayList在文本文件中的样子:

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

回答by Jeff

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,

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

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.

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

回答by Brian Agnew

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.

目前尚不清楚您的问题有什么问题。但是,我希望您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);
               }  
          }

回答by RichH

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:

我注意到的事情:

  1. You i2 loop should be for (i2 = 0; i2 < theword.length; i2 += 2) {
  2. I wouldn't set the initial size of the ArrayList unless you know how many items are in the file.
  3. Are there two spaces between your username and password?
  4. Have you looked into serialization?
  5. Why not have a new line for each username and password It would be a lot easier to load.

    username1
    password1
    username2
    password2

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

    用户名1
    密码1
    用户名2
    密码2