0

I am having some issues in terms of appending data into my CSV file. The problem is that whenever I try to append data into my CSV file on a second time, the second value which is appended to the CSV file comes with the first appended value. It's like it brings the existing value with it when appending to the CSV file. Thus, because of this issue, it results into an array index out of bounds exception in this statement: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; , the data of the CSV file repeats the existing values along with the latest appended values and also the first value is only displayed on my GUI table.

CSV File: CSV File

Table:

Table

Here's my source code in writing and reading the CSV:

public void writeCustomerCSV(){  // this creates a CSV file which stores the inputs of the user
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv",true)); // when I set append mode to true,  cust[read2DStringIndex][newVarIndexer] = fromfile[g] results to index array out of bounds to 10
        StringBuilder sb = new StringBuilder();
        int y;
        for(int x = 0; x < itemTo2D.length; x++){
            if(itemTo2D[x][0] != null){
                for(y = 0; y < itemTo2D[0].length; y++){
                    sb.append(itemTo2D[x][y]);
                    sb.append(",");
                }
            }
            sb.append("-");  //separation for rows
            sb.append(",");  // separation for columns
        }
        bw.write(sb.toString());
        bw.close();
    }
    catch (Exception ex){
    }
}

public void readCustomerCSV(){  // reads the contents of the CSV file 
    String[][] twoDArray = new String[10][7];
    int read2DStringIndex = 0;
    int newVarIndexer = 0;
    DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel();  // table
    String[] fromfile = {};   // 1d string for getting the columns(7 columns) of the CSV file
    int ak = 0;
    int sk = 0;
    try{
        BufferedReader br = new  BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
        String line;
        while ((line = br.readLine()) != null){
            fromfile = line.split(",");  //separates the columns by a comma
            for(int c = 0; c < fromfile.length; c++){
                if(fromfile[c].equals("-")){
                    sk = 0;
                    ak++;
                    if(c > 0){
                        if(!fromfile[c-1].equals("-")){
                            id = id + 1;
                        }
                    }
                } else{
                    twoDArray[ak][sk] = fromfile[c];
                    sk++;
                }
            }
        }
    } catch (Exception ex){

    }
    for(int g = 0; g < fromfile.length; g++){  
        if(fromfile[g].equals("-")){   //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
            read2DStringIndex++;
            newVarIndexer = 0;
        }
        else{
            cust[read2DStringIndex][newVarIndexer] = fromfile[g];    //cust is the 2D array(declared universal) which is going to display the values to the table
            newVarIndexer++;
        }
    }
    for(int h = 0; h < cust.length; h++){  //prints cust (2D array) , just to check what data is being stored
        for(int p = 0; p < cust[0].length; p++){
            System.out.println(cust[h][p] + ",");
        }
    }
    setrowcount = 0;
    for(int r = 0; r < cust.length; r++){
        if(setrowcount == 0){
            tblmodelll.setRowCount(0);
        }
        try{                
            if(cust[r][0].equals("null") == false){  
                tblmodelll.addRow(cust[r]);  //displays the cust(2D array) data to table 
            }
        } catch(Exception e){
            
        }
        setrowcount++; 
    }
}

Is there something missing in my structure of the codes or is my logic in appending the values not right? Your responses would indeed help me in resolving this issue. Thank you very much.

Ralph Henry
  • 122
  • 1
  • 13
  • Does this answer your question? [Create a new line in Java's FileWriter](https://stackoverflow.com/questions/18549704/create-a-new-line-in-javas-filewriter) – Kaustubh Khare Apr 08 '21 at 06:27
  • 1. Check if file streams are flushed/closed. 2. Replace\Refactor arrays with a collection. – Oleks Apr 08 '21 at 07:46
  • @Abra , my bad for not posting the the content of that line, I added it now on the post, anyway here it is: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; – Ralph Henry Apr 08 '21 at 12:23
  • @KaustubhKhare , I think not really, I am trying to append the values on the same line but without appending again the existing value along with the newly appended value. – Ralph Henry Apr 08 '21 at 12:48
  • @Oleksandr hello, I'm a bit confused on how to replace/refactor arrays with a collection, does it involve with combining up statements? – Ralph Henry Apr 08 '21 at 12:58
  • @RalphHenry I think you need to create one more object of `StringBuilder`(inside 1st for loop) to hold each row data and append it to the existing `StringBuilder` object `sb`. Creating new object/flushing will not be having existing data. – Kaustubh Khare Apr 09 '21 at 04:13
  • @KaustubhKhare you mean that I need to declare another stringbuilder to be appended to the existing stringbuilder sb?? Also, you mean the first for loop in writing the CSV? I'm a bit confused, excuse me for this... – Ralph Henry Apr 09 '21 at 05:20
  • @RalphHenry Yes, declared another stringbuilder will be having only the current row and append it into existing sb. Correct, first for loop in writing the CSV. – Kaustubh Khare Apr 09 '21 at 06:15

0 Answers0