writing a csv file using Buffered writer in Java
Asked Answered
A

3

9

I am writing a csv file using buffered writer in java. My data is written correctly but I want to have different columns under which the data comes, Currently it is writing each instance of date in one row but not separated by columns.

The code is

  DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");  
        File file = new File( dirName + "\\"+ df.format(new Date()) +"_Statistics.csv");  
        if ( !file.exists() )
            file.createNewFile();

        FileWriter fw = new FileWriter(file);
        writer = new BufferedWriter( fw );
        writer.write("Message Source");
        writer.write("Message Name");
        writer.write("Component");
        writer.write("Occurance");
        writer.write("Message Payload");
        writer.write("Bandwidth (Payload)");
        writer.write("Message Payload with Header");
        writer.write("Bandwidth (Payload with Header)");
        writer.newLine();
        for (Signal signal : messages) {
            writer.write(signal.getSource());
            writer.write(signal.getName());
            writer.write(signal.getComponent());
            writer.write(Integer.toString(signal.getOccurance()));
            writer.write(Integer.toString(signal.getSize()));
            writer.write(Float.toString(signal.getBandwidth()));
            writer.write(Integer.toString(signal.getSizewithHeader()));
            writer.write(Float.toString(signal.getBandwidthWithHeader()));
            writer.newLine();
        }
        writer.flush();
        writer.close();
        fw.close();

Is there any way to separate the data column wise so that it is properly readable?

EDIT

Instead of using buffered writer I use CSVReader library for java. http://www.csvreader.com/java_csv.php The code now is

  DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");  
        File file = new File( dirName + "\\"+ df.format(new Date()) +"_Statistics.csv");  
        if ( !file.exists() )
            file.createNewFile();

        // Use FileWriter constructor that specifies open for appending
        CsvWriter csvOutput = new CsvWriter(new FileWriter(file, true), ',');

        //Create Header for CSV
        csvOutput.write("Message Source");
        csvOutput.write("Message Name");
        csvOutput.write("Component");
        csvOutput.write("Occurance");
        csvOutput.write("Message Payload");
        csvOutput.write("Bandwidth (Payload)");
        csvOutput.write("Message Payload with Header");
        csvOutput.write("Bandwidth (Payload with Header)");
        csvOutput.endRecord();
        for (Signal signal : messages) {
            csvOutput.write(signal.getSource());
            csvOutput.write(signal.getName());
            csvOutput.write(signal.getComponent());
            csvOutput.write(Integer.toString(signal.getOccurance()));
            csvOutput.write(Integer.toString(signal.getSize()));
            csvOutput.write(Float.toString(signal.getBandwidth()));
            csvOutput.write(Integer.toString(signal.getSizewithHeader()));
            csvOutput.write(Float.toString(signal.getBandwidthWithHeader()));
            csvOutput.endRecord();
        }
        csvOutput.flush();
        csvOutput.close();

It properly formats the data but the problem is now when I run the code for 2nd time a 2nd file is created and the new file contains duplicated rows, for every row in the first file there are 2 rows in the 2nd file with similar data.

Is that I am not cleaning some resources ?

Thanks

Artificial answered 26/9, 2013 at 11:50 Comment(7)
Columns should be separated by a commaTestament
@Testament you mean after every write I should do writer.write(",");Artificial
You could do that - it appears they are missing in the column names, and in the data. In order for the document to format correctly each column should be delimited by a comma. For a .csv anywayTestament
Well, tim already answered the first part of your question. Now for the second part (duplicated rows), I would bet that between runs you're not cleaning the messages variable. I would also recommend to rethink the exception management, you should always close resources in a finally block, this way, if an exception occurs, you don't leave anything open. However, with the information you're giving, it does not seem to be the problem.Remora
Didn't you forget to clear() the messages? Maybe you are just adding items to it and that is the reason why it's duplicated.Rodroda
You don't need to test for existence or call File.createNewFile(). Calling new FileWriter() already does both. You're just adding redundant processing, and wasting time and soace.Bellows
Are your messages coming properly?Ermelindaermengarde
H
1

When writing a csv file you need to enclose your data like this

csvOutput.write("\"");
csvOutput.write(signal.getSource());
csvOutput.write("\"");
csvOutput.write(",\"")
csvOutput.write("\"");
csvOutput.write(signal.getName()
csvOutput.write("\"");

And you need to do this because if there is a comma within a data it would cause a problem while parsing and cause data to be lodged in a different columns. Also make sure inside finally block

finally {
//csvOutput is closed here

}
Hade answered 24/1, 2017 at 17:30 Comment(0)
D
0

If you want to have a seperate coloumn in Excel, for the fields that you have written in your code so instead of fw.append(","); Just give fw.append(";"); It will work and for setting the Header, instead of creating a variable like String f="Id, Name, Salary" and passing that variable to the method fw.append(f); Simply pass the fields instead of creating the variable like fw.append("Id; Name; Salary") using semicolon.

Dispose answered 23/5, 2016 at 7:38 Comment(0)
I
-1

From what I understand your actual data isn't lining up with the columns, because there is no way for it to know how wide the column is.

You could try using tabs, or predefine the width of each column (like make them all 10 characters).

Incubation answered 26/9, 2013 at 12:2 Comment(1)
Yes something like writer.write("\t"); (tab character)Chamfron

© 2022 - 2024 — McMap. All rights reserved.