0

Suppose I have ArrayList with following contents

public void add() {

    obj.add(1);
    obj.add(123456789);
    obj.add(1.222);
    obj.add(2.333);  

    obj.add(2);
    obj.add(9876541);
    obj.add(4.555);
    obj.add(7.888);



}

I want the contents of the ArrayList to be written in the txt file as follows

1,123456789,1.222,2.333
2,9876541,4.555,7,888 

I have following code to write the contents to the file

  public void createCSV() {

    try {
        FileWriter fos = new FileWriter(
                "/home/data.txt");
        PrintWriter out = new PrintWriter(fos);

        for (int i = 0; i < obj.size(); i++) {

            out.write(String.valueOf(obj.get(i)));
            out.write(",");

        }
        out.close();

    } catch (Exception e) {

    }
}

public static void main(String[] args) {

    JavaOp_CSV x = new JavaOp_CSV();
    x.add();
    x.createCSV();

}

As of now the contents in the file is

1,123456789,1.222,2.333,

Can anybody provide me with a logic to get the o/p as mention above?? Thanks in advance

3
  • 1
    Is the question 'how to get rid of the last comma' or 'How to insert an enter after 4 fields' or even something else? Commented Mar 2, 2012 at 9:46
  • 1
    I think you should use a different structure. I suppose that your 1 and 2 are "rows" in the output. Commented Mar 2, 2012 at 9:47
  • I would like to get rid of the comma and to insert enter after 4 fields too Commented Mar 2, 2012 at 9:56

2 Answers 2

3

Use a StringBuilder to build the string you will later write to file, and keep a count i on the elements.

if i % 4 == 0 - add a line break
else: add a ','.

Note: You need to avoid adding the new line at the first element, and possibly the last as well if total_num_elements % 4 != 0

It can be easily done duing post processing using StringBuilder.deleteCharAt()

Sign up to request clarification or add additional context in comments.

Comments

2

You can also try org.apache.commons.lang.StringUtils, it has a join method that meets your need.

StringUtils.join(obj.toArray(), ',');

Or you can only determine whether it's the first element or the last element.

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.