java - 从文本文件读取字符串值到 Java 中的 java arraylist

标签 java arraylist

我想通过拆分 | 来读取字符串值,包括文本文件中的空格并存储到 Account 类。这是我读取文本文件的函数。

public ArrayList<Account> loadAccount(String fn) throws IOException{     
    ArrayList<Account> account = new ArrayList<Account>();
    Scanner infile = new Scanner(new InputStreamReader (new FileInputStream(fn)));
    while(infile.hasNextLine()){
        String accountNo = infile.nextLine();
        String legencyNo = infile.nextLine();
        Account c = new Account(accountNo, legencyNo);
        account.add(c);
    }
    infile.close();
    return account;
}     

这是 Account 类。

public class Account {
 private int id;
 private String accountNo;
 private String legencyNo;
}

这是 AccountInformation.txt。

帐号 |遗留 key |说明

80000001|7001111|

80000002| |

80000003|7001234|测试

更新:这是我的 readFile 类。现在,没问题了。我正在使用 StringUtils。

public static List<Account> readFile() {

    String file = "C:\\Dev\\JBoss\\UpdateAccountNumber\\source\\AccountInformation.txt";
    BufferedReader br = null;
    String line = "";
    String splitter = "\\|";
    List<Account> accountList = new ArrayList<Account>();
    try {
        br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {
            String[] accounts = org.apache.commons.lang3.StringUtils.split(line, splitter);
            String accountNo = "",legencyNo="";
            for(int i = 0;i<accounts.length;i++){
                if (i == 0){
                     accountNo = (accounts[0] == null) ? "" : accounts[0];
                }
                if (i==1){
                     legencyNo = (accounts[1] == null) ? "" : accounts[1];
                }
            }
            Account a = new Account(accountNo,legencyNo);
            accountList.add(a); 
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return accountList;
  }

最佳答案

试试吧。这意味着 split string include space .

String[] accounts = line.split(splitter, -1);

关于java - 从文本文件读取字符串值到 Java 中的 java arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28276570/

相关文章:

java - 尝试将卡片与其图像映射时出现错误

java - 尝试将 Double 解析为 String 时出现 ArrayOutOfBounds 异常

java检查值

java - 如何从嵌套的ArrayList中获取JSONObject的属性并将其显示给ListView?

c# - StreamReader 使用数组列表或数组

java - 请求范围的 ContainerRequestFilter

java - 以 Reader 方式打开 InputStream

java - 无法根据 Android Studio 中的加速度计数据更新应用程序

java - 旧版 OpenGL 纹理

java - Swing wait()/notifyAll()