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

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Wearybands
  • 2,438
  • 8
  • 34
  • 53
  • 4
    Columns should be separated by a comma – tim Sep 26 '13 at 11:59
  • @tim you mean after every write I should do writer.write(","); – Wearybands Sep 26 '13 at 12:01
  • 2
    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 anyway – tim Sep 26 '13 at 12:02
  • 1
    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. – Martin Sep 26 '13 at 12:48
  • 1
    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. – TomasZ. May 04 '14 at 09:00
  • 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. – user207421 Jan 20 '15 at 04:35
  • Are your messages coming properly? – Samurai Jan 29 '16 at 13:42

3 Answers3

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

}
shashwatZing
  • 1,550
  • 1
  • 17
  • 24
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.

manniL
  • 7,157
  • 7
  • 46
  • 72
-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).

slaw
  • 611
  • 2
  • 7
  • 20