如何从文件读取数组形成集合


ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("accounts.dat"));

//从文件accounts.dat中 读取Account2的对象,形成数组inputAccountsList
ArrayList<Account2> inputAccountsList = (ArrayList<Account2>) inputStream.readObject();
inputStream.close();

//抛出捕获 EOFException
try {
    inputAccountsList = (ArrayList<Account2>) inputStream.readObject();
} catch (EOFException ex) {}

//判断该系统内是否存在账户
if (inputAccountsList.size() == 0) {
    System.out.println("The system does not have any accounts,please add an account first.");

} else {
    System.out.print("Please enter your id:");
    int id = input.nextInt();
    System.out.print("Please enter your password:");
    String password = input.next();

    boolean log = true;
    while (log) {
        for (int i = 0; i < inputAccountsList.size(); i++) {
            if (inputAccountsList.get(i).getId() == id) {
                if (inputAccountsList.get(i).getPassword().equals(password)) {
                    account2.setId(id);
                    account2.setPassword(password);
                }
            } else {
                System.out.println("The account or password is incorrect.");
                System.out.println("Please log in again");
                log = false;
            }
        }
    }
}

如果你文件里面的数据是数组形式的数据,直接读出来转化成字符串,再转成集合就可以了;如果你的文件中不是数组形式,要抓取某部分数组来作为集合,你就得解析数据,然后取某部分的数据,然后组装成集合就可以了