Java 将计算列添加到 CSV 文件

标签 java csv duration

如何向 CSV 文件添加新列,并在每列中添加计算数据?

示例

用户 ID,expDate 1,012015 2,022016 3,032018

我将从每一行中获取expDate,相对于当前月份和年份计算它以获得到期前的月份数,然后舍入monthsTill(因此下个月的monthsTill将为1,无论是第一天还是最后一天当月)

用户 ID、expDate、monthsTill 1,022017,0 2,032017,1 3,042017,2 3,052017,3

另外,您如何“跳过”在相应列中具有特定值的行?

最佳答案

根据您的伪代码,这应该可以解决问题

private void process(){
    BufferedReader bufferedReader = null;
    PrintWriter p = null;
    String sep = ",";
    String newCol = "monthsTill";
    String defaultTillExpMonth = ">3";
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    int currMonth = cal.get(Calendar.MONTH) + 1;
    try {
    // read csv file
    List<String> input = new ArrayList<String>();
   File inputFile = new File("InputFile");
  bufferedReader = new BufferedReader(new FileReader(inputFile));
    String readLine = "";
    while ((readLine = bufferedReader.readLine()) != null) {
        input.add(readLine);
    }

 // for each row after first row
    // calculate timeTillExpired
        // if format MYYYY (ex 22017)
            // M and YYYY -> MM and YYYY

       // calculate relative to current date as months

    int numOfRecords = input.size();
    if(numOfRecords>1){
        List<String> output = new ArrayList<String>();
        String header = input.get(0) +sep +newCol;
        output.add(header);

        // for each row after first row
        // calculate timeTillExpired
        // if format MYYYY (ex 22017)
              // M and YYYY -> MM and YYYY
        // calculate relative to current date as months
        for(int i=1;i<numOfRecords;i++){
            // I am simply going to get the last column from record
            String row = input.get(i);
            StringBuilder res = new StringBuilder(row);
            String [] entries = row.split(sep);
            int length = entries.length;
            if(length>0){
                res.append(sep);
                String rec = entries[length-1];
                int expMonth = 0;
                // Case of MYYYY. Assumption is it's either MYYYY or MMYYYY
                if(rec.length()==5){
                    expMonth = Integer.valueOf(rec.substring(0, 1));
                } else {
                    expMonth = Integer.valueOf(rec.substring(0, 2));
                }

                int monToExp = expMonth - currMonth;
                // if calculated > 3
                if(monToExp > 3){
                    res.append(defaultTillExpMonth);
                } else {
                    res.append(monToExp);
                }
                output.add(res.toString());
            }
        }
        // Write into the same file.
        // First We'll delete everything in the input file and then write the modified records

        p = new PrintWriter(new FileWriter("output.txt",false));
        // Ouch. Very bad way to handle resources. You should find a better way
        p.print("");
        p.close();
        // Write into file
        p = new PrintWriter(new FileWriter("InputFile"));
        for(String row : output)
        {
            p.println(row);
        }



    } else {
        System.out.println("No records to process");
    }



    } catch(IOException e){
        e.printStackTrace();
    } finally { // Close file
        if(p!=null){
            p.close();
        }
        if(bufferedReader!=null){
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

我强烈建议您了解什么是文件资源、如何有效地处理它们并改进此代码。稍后您应该迁移到 Apache Commons Library

关于Java 将计算列添加到 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460571/

相关文章:

java程序输出偶数/奇数

sql - 通过 shellscript 将 CSV 导入 SQLite,主键问题和重复数据

Java - 解析日期/期间的优雅方式?

java - 用于访问 volatile 实例变量的局部变量

java - Android unregisterReceiver 与 onPause

java - 如何在Java应用程序中获取机器上的SID列表

python - 编写 CSV Python

python-3.x - Python 3.6 使用请求模块从finance.yahoo.com下载.csv文件

java - 如何在 Java 中获取数组中所有持续时间的总和?

WPF - window.IsEnabled setter 持续时间长