Java - Writing strings to a CSV file

前端 未结 7 2311
野趣味
野趣味 2020-11-28 10:45

I am trying to write data to a csv file with java, however when I try opening the produced file with excel I am getting an error saying the file is corrupt. Upon opening the

7条回答
  •  旧时难觅i
    2020-11-28 11:23

    Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunning your program, you may want to try this

    public void writeAudit(String actionName) {
        String whereWrite = "./csvFiles/audit.csv";
    
        try {
            FileWriter fw = new FileWriter(whereWrite, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
    
            Date date = new Date();
    
            pw.println(actionName + "," + date.toString());
            pw.flush();
            pw.close();
    
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题