-1

I have a csv file and I have some data in it and I want to append a column in it. e.g:

Name,Age,Marks
Joe,15,1
Smith,20,2

I want to append that Marks Column through code. The problem I'm getting is

Name,Age,Marks
Joe,15
1
2
Smith,20
1
2

The data is getting written 2 times and also the on the first column (Except the first one). How can I prevent it from doing it ? I've been stuck in this problem from past 1 week
My code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class appendCol {
    public static String appendingCol() {
        String stringArray[] = {"Marks", "1", "2"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < stringArray.length; i++) {
            sb.append(stringArray[i]);
        }
        String str = sb.toString();
        return str;
    }

    public static void main(String[] args) throws IOException {
        String line = "";
        BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
        try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {
            while ((line = br.readLine()) != null) {
                String newFileLine = line + "," + appendingCol();
                writer.write(newFileLine);
                writer.newLine();
            }
        }
        writer.close();
    }
}
5
  • 1
    CSV file means you should use a CSV Library to read and write the file. Commented Jun 23, 2021 at 16:34
  • I tried but couldn't find a solution. Commented Jun 23, 2021 at 16:36
  • You've shown the after, but not the before. I think I understand the before state, but it would help your question a lot if you showed the before state, the expected after state, and the actual after state. I'm making assumptions about the before state, but we know "assumptions are the mother of all foul-ups". Also, I don't think this has anything to do with the eclipse tag. Commented Jun 23, 2021 at 16:42
  • 1
    Does this answer your question? Java append new column to csv file Commented Jun 23, 2021 at 16:48
  • 1
    I down voted because No research Commented Jun 23, 2021 at 16:48

3 Answers 3

1

With this as input in text1.csv:

Name,Age
Joe,15
Smith,20

I ran (very tightly adapted from your code):

   static void tryStackOverflow () {
      String line = "";
      try {
         BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv"));
         BufferedReader br = new BufferedReader (new FileReader ("text1.csv"));
         while ((line = br.readLine ()) != null) {
            String newFileLine = line + "," + appendingCol ();
            writer.write (newFileLine);
            writer.newLine ();
         }
         writer.close ();
      } catch (IOException excep) {
         System.err.println ("Exception " + excep);
      }
   }


   public static String appendingCol () {
      String stringArray[] = { "Marks", "1", "2" };
      StringBuilder sb = new StringBuilder ();
      for (int i = 0; i < stringArray.length; i++) {
         sb.append (stringArray [i]);
      }
      String str = sb.toString ();
      return str;
   }

and that produced:

Name,Age,Marks12
Joe,15,Marks12
Smith,20,Marks12

Then it seems clear that stringArray should be be in the other method (your main method) and added to line by line. Your code also assumes there are as many lines as elements in that array. But disregarding that, I moved the array and eliminated the appendingCol method and ran this:

   static void tryStackOverflow () {
      String line = "";
      String stringArray[] = { "Marks", "1", "2" };
      int lineNum = 0;
      try {
         BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv"));
         BufferedReader br = new BufferedReader (new FileReader ("text1.csv"));
         while ((line = br.readLine ()) != null) {
            String newFileLine = line + "," + stringArray [lineNum++];
            writer.write (newFileLine);
            writer.newLine ();
         }
         writer.close ();
      } catch (IOException excep) {
         System.err.println ("Exception " + excep);
      }
   }

which produced this:

Name,Age,Marks
Joe,15,1
Smith,20,2
Sign up to request clarification or add additional context in comments.

Comments

1

The header needs to be handled separately from the values.

public static void main(String[] args) throws IOException {

Map<String, String[]> csvCol = new HashMap<String, String[]>();
String stringArray[] = { "1", "2" };
csvCol.put('Marks', stringArray);


String line = "";
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {


    String headers = "";
    String values = "";
    String newFileLine ="";
    bool isHeader=true;
    while ((line = br.readLine()) != null) {
        if(isHeader){
           csvCol.forEach((k,v) -> {
              headers = "," + k ;
           });
              newFileLine = line + headers ;
         }else{
           csvCol.forEach((k,v) -> {
              values = "," + v ;
           });
           newFileLine = line + values;
           isHeader = false;
         }
        writer.write(newFileLine);
        writer.newLine(); 
    }
}
writer.close();
}

2 Comments

What should be the type of values variable ?
Bro its just writing the header all the way from top to down. I made the headers and values static because it was giving me error. How can I resolve this ?
0

This problem requires one more column to be appended to the original CSV. The Java implementation is longer in code. However, it is easy to write with the open-source package SPL under Java, as long as one sentence:

+ A
1 =file("temp.csv").export@wc(file("test1.csv").import@wc().(~|="Marks,1,2".split@c()(#)))

SPL provides JDBC for JAVA to call, save the above script as append.splx, and call the script file as a stored procedure in JAVA:

…

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st=con.prepareCall("call append()");

st.execute();

…

Or directly execute the SPL string in SQL in JAVA:

…    
st = con.prepareStatement("==file(\"temp.csv\").export@wc(file(\"test1.csv\")
.import@wc().(~|=\"Marks,1,2\".split@c()(#)))");

st.execute();    
…

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.