簡體   English   中英

如何從數組列表讀取和寫入對象?

[英]How can I read and write objects from an arraylist?

我在UserArchive類中創建一個arraylist,並從User類中添加User-objects:

public class UserArchive implements Serializable {
ArrayList<User> list = new ArrayList<User>();

// Inserts a new User-object
public void regCustomer(User u) {
    list.add(u);
}

讀寫此列表的最佳方法是什么?

我認為這是正確的書寫方式嗎?

    public void writeFile() {
    File fileName = new File("testList.txt");
    try{
        FileWriter fw = new FileWriter(fileName);
        Writer output = new BufferedWriter(fw);
        int sz = list.size();
        for(int i = 0; i < sz; i++){
            output.write(list.get(i).toString() +"\n");
        }
        output.close();
    } catch(Exception e){
        JOptionPane.showMessageDialog(null, "Kan ikke lage denne filen");
    }

我嘗試使用BufferedReader讀取文件,但是無法使list.add(line)正常工作:

    public void readFile() {
    String fileName = "testList.txt";
    String line;

    try{
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        if(!input.ready()){
            throw new IOException();
        }
        while((line = input.readLine()) != null){
            list.add(line);
        }
        input.close();
    } catch(IOException e){
        System.out.println(e);
    }
}

我知道問題是那行是一個字符串,應該如何成為用戶。 是我不能使用BufferedReader做到這一點的問題嗎? 如果是這樣,我應該如何讀取文件?

如果用戶對象不復雜,最簡單的方法是將每個用戶轉換為csv格式。

例如,您的用戶類應如下所示

public class User {

private static final String SPLIT_CHAR = ",";
private String field1;
private String field2;
private String field3;

public User(String csv) {
    String[] split = csv.split(SPLIT_CHAR);
    if (split.length > 0) {
        field1 = split[0];
    }

    if (split.length > 1) {
        field2 = split[1];
    }

    if (split.length > 2) {
        field3 = split[2];
    }
}

/**
 * Setters and getters for fields
 * 
 * 
 */

public String toCSV() {
    //check null here and pass empty strings
    return field1 + SPLIT_CHAR + field2 + SPLIT_CHAR + field3;
}

  }



}

在編寫對象調用時
output.write(list.get(i).toCSV() +"\\n"); 閱讀時可以調用list.add(new User(line));

想象一個簡單的User類,如下所示:

public class User {
    private int id;
    private String username;

    // Constructors, etc...

    public String toString() {
        StringBuilder sb = new StringBuilder("#USER $");
        sb.append(id);
        sb.append(" $ ");
        sb.append(username);
        return sb.toString();
    }
}

對於id = 42username = "Dummy"的用戶,用戶的String表示為:

#USER $ 42 $ Dummy

乍一看,您的代碼似乎已成功將這些字符串寫入文本文件(我尚未對其進行測試)。
因此,問題在於回讀信息。 從(在這種情況下)格式化文本中提取有意義的信息通常被稱為parsing

您想從閱讀的行中解析此信息。
修改您的代碼:

BufferedReader input = null;
try {
    input = new BufferedReader(new FileReader(fileName));
    String line;
    while((line = input.readLine()) != null) {
        list.add(User.parse(line));
    }
} catch(IOException e) {
    e.printStackTrace();
} finally {
    if (input != null) { input.close(); }
}

注意細微的差別。 我已經用list.add(User.parse(line))替換了list.add(line) list.add(User.parse(line)) 這就是魔術發生的地方。 讓我們繼續並實現解析方法。

public class User {
    private int id;
    private String username;

    // ...

    public static User parse(String line) throws Exception {
        // Let's split the line on those $ symbols, possibly with spaces.
        String[] info = line.split("[ ]*\\$[ ]*");
        // Now, we must validate the info gathered.
        if (info.length != 3 || !info[0].equals("#USER")) {
            // Here would go some exception defined by you.
            // Alternatively, handle the error in some other way.
            throw new Exception("Unknown data format.");
        }
        // Let's retrieve the id.
        int id;
        try {
            id = Integer.parseInt(info[1]);
        } catch (NumberFormatException ex) {
            throw new Exception("Invalid id.");
        }
        // The username is a String, so it's ok.
        // Create new User and return it.
        return new User(id, info[2]);
    }
}

大功告成!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM