Parse date from file using java split

257 Views Asked by At

I have code that parses a file then inserts the rows into a table. I ignored the first row originally because it had just the date and useless data. I want to now take the date and insert it into all the rows in my table but don't know how to really do that. I know I will need to edit my entity to include the date but don't know how to edit my code to parse the date or if its better to have a new method that does just the inserting of the date.

file format

20200310|extra|extra|extra||
Mn1223|01192|windows|extra|extra|extra||
Sd1223|02390|linux|extra|extra|extra||
2

current table

account_name      command_name   system_name    createDt
Mn1223            01192          windows        NULL
Sd1223            02390          linux          NULL

I want the 20200310 inserted into the createDt

Entity/model

public ZygateEntity(String accountName, String commandName, String systemName){
        this.accountName=accountName;
        this.commandName=commandName;
        this.systemName=systemName;
    }

   //getters and setters

Parse file method

   private List<ZygateEntity> parseZygateData() throws IOException {
        String filePath = "C:\\DEV\\Test_file.xlsx";

        List<String> lines = Files.readAllLines(Paths.get(filePath));

        // remove date and amount
        lines.remove(0);
        lines.remove(lines.size() - 1);

        return lines.stream()
                .map(s -> s.split("[|]")).map(val -> new ZygateEntity(val[0],val[1],val[2])).collect(Collectors.toList());
    }

insert method

public void insertZygateData(List<ZygateEntity> parseData) {
    String sql = "INSERT INTO Landing.midrange_xygate_load (account_name,command_name,system_name)"+
            "VALUES (:account_name,:command_name,:system_name)";

    for (ZygateEntity zygateInfo : parseData){
        SqlParameterSource source = new MapSqlParameterSource("account_name", zygateInfo.getAccountName())
                .addValue("command_name", zygateInfo.getCommandName())
                .addValue("system_name", zygateInfo.getSystemName());
        namedParameterJdbcTemplate.update(sql, source);
    }
}
1

There are 1 best solutions below

4
On BEST ANSWER

java.time

    // remove date and amount
    String dateLine = lines.remove(0);
    String dateString = dateLine.split("[|]")[0];
    LocalDate date
            = LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE);
    lines.remove(lines.size() - 1);

This gives you a LocalDate object ready to insert with every line.

java.time is the modern Java date and time API and has a built-in formatter for your date format, 20200310: DateTimeFormatter.BASIC_ISO_DATE.