簡體   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