Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading string value from a text file to java arraylist in Java

Tags:

java

arraylist

I want to read string value by splitting | include white space from text file and store to Account class.This is my function for read text file.

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;
}     

This is Account class.

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

This is AccountInformation.txt.

Account Number | Legacy Key | Description

80000001|7001111|

80000002| |

80000003|7001234|Testing

Update: This is my readFile class.Now, It's ok.I'm using 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;
  }
like image 496
Kyaw Bo Avatar asked Apr 10 '26 15:04

Kyaw Bo


1 Answers

Just try as. Which mean split string include space .

String[] accounts = line.split(splitter, -1);
like image 125
Zaw Than oo Avatar answered Apr 13 '26 04:04

Zaw Than oo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!