0

well, opencsv kinda works, exept for writing only one line at a time, deleting the previous information. if I want a csv like:

CAR, YEAR, MODEL

mazda,1996,model a

ferrari,1998, model b

so what i get is only the last line every time, no matter how much information I put in. the code is like:

try {
             File traceFile = new File(((Context)this).getExternalFilesDir(null), FILE_NAME);
             CSVWriter writer = new CSVWriter(new FileWriter(traceFile));
              String[] entries = array_body.split("#");
              writer.writeNext(entries);
             writer.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        } 

and according to the tutorials and examples that I saw this code suppose to work, help please?

array_body is "part_a#part_b#part_c"

arvivlx2
  • 139
  • 1
  • 10

2 Answers2

1

I'm assuming this is in a loop? You create a new writer, then write a single line. So, yes, it will just have one line in it. Move the new CSVWriter outside of the loop. If that isn't the issue, please show rest of your code since the problem you describe would seem to have to do with your loop structure.

Beel
  • 1,000
  • 12
  • 23
  • I c'ant share the whole relevant code here, it is big. I just keep the data that the user is putting every time he create a character in the app. every character is a line of data in the csv. the code that i posted isn't in loop, it suppose to add a new line whenever the user enter the app. when I used normal filewriter it worked good, but with opencsv it's not working and i dont know why – arvivlx2 Jul 25 '15 at 20:09
1

It works for me - are you sure you don't accidentally have the new FileWriter inside your read loop?

public void create(int numRecords, FileWriter fos) {
    CSVWriter writer = new CSVWriter(fos);
    writer.writeNext(SmallRecordGenerator.generateHeader());
    for (int i = 1; i <= numRecords; i++) {
        SmallRecord record = SmallRecordGenerator.createRecord(i);
        writer.writeNext(record.convert());
    }
}
Scott Conway
  • 975
  • 7
  • 13