我想通过拆分 |
来读取字符串值,包括文本文件中的空格并存储到 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/