how to write String values to csv file in java

googleart
googleart used Ask the Experts™
on
I have situation where i  need to write the values from database to csv file.I am putting all the values in a String.My String out put looks like [event1=0,event2=4,event3=5.............]
Event equal value is count.Now i need to write those values in to csv file as below

event   count

event1  0

event2  4

event3  5

and so on.can anyone help me how to do that
I tried to use supercsv but i am not able write the data in to the file
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Awarded 2011
Awarded 2011

Commented:
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.StringTokenizer;

public class ParseEventString {
    public static void main(String[] args) {
        try{
            PrintStream psout = new PrintStream(new FileOutputStream("out.csv"));
            String s=    "event1=0,event2=4,event3=5";
            StringTokenizer t = new StringTokenizer(s,"=,");
            psout.println("Event,Count");
                  while(true){
                      if(t.hasMoreTokens()){
                          psout.println(t.nextToken()+","+t.nextToken());
                      } else break;
                  }

             psout.close();


        }   catch(Exception ex){
            ex.printStackTrace();
        }

    }

}

Open in new window

Contents of out.csv:
Event,Count
event1,0
event2,4
event3,5

Open in new window

Awarded 2011
Awarded 2011
Commented:

If you have the opening and closing brcaket we can take care of it ion this way:


import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.StringTokenizer;

public class ParseEventString {
    public static void main(String[] args) {
        try{
            PrintStream psout = new PrintStream(new FileOutputStream("out.csv"));
            String s1=    "[event1=0,event2=4,event3=5]";
               String s = s1.substring(1,s1.indexOf("]"));
            StringTokenizer t = new StringTokenizer(s,"=,");
            psout.println("Event,Count");
                  while(true){
                      if(t.hasMoreTokens()){
                          psout.println(t.nextToken()+","+t.nextToken());
                      } else break;
                  }
            

     
             psout.close();


        }   catch(Exception ex){
            ex.printStackTrace();
        }

    }

}

Open in new window


Awarded 2011
Awarded 2011

Commented:

Another option is to use split(regex) method of class String:
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.StringTokenizer;

public class ParseEventString {
    public static void main(String[] args) {
        try{
            PrintStream psout = new PrintStream(new FileOutputStream("out.csv"));
            String s1=    "[event1=0,event2=4,event3=5]";
               String s = s1.substring(1,s1.indexOf("]"));
                     psout.println("Event,Count");
                      

            String [] array = s.split("[=,]");
            for(int i=0; i<array.length; i=i+2) {
                psout.println(array[i] + "," + array[i+1]);
            }
          
             psout.close();


        }   catch(Exception ex){
            ex.printStackTrace();
        }

    }

}

Open in new window


Contents of output file:
Event,Count
event1,0
event2,4
event3,5

Open in new window

Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Awarded 2011
Awarded 2011

Commented:


And one more solution:
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.StringTokenizer;

public class ParseEventString {
    public static void main(String[] args) {
        try{
            PrintStream psout = new PrintStream(new FileOutputStream("out.csv"));
            String s1=    "[event1=0,event2=4,event3=5]";

            psout.println("Event,Count");


            String [] array = s1.split("[=,\\[\\]]");
            for(int i=1; i<array.length-1; i=i+2) {
                psout.println(array[i] + "," + array[i+1]);
            }
           
             psout.close();


        }   catch(Exception ex){
            ex.printStackTrace();
        }

    }

}

Open in new window


Output is of course the same:
Event,Count
event1,0
event2,4
event3,5

Open in new window

Top Expert 2016

Commented:
Write the csv directly from the ResultSet or it's inefficient. Try something like
public static void resultSetToCsv(ResultSet rs, Writer out) {
		try {
			final String LINEFEED = System.getProperty("line.separator");
			ResultSetMetaData metaData = rs.getMetaData();
			int numberOfColumns = metaData.getColumnCount();

			// Get the column names
			String sep = "";

			for (int column = 0; column < numberOfColumns; column++) {
				System.out.print(sep);
				System.out.print(metaData.getColumnLabel(column + 1));
				sep = ",";
			}

			out.write(LINEFEED);

			// Get all rows.
			while (rs.next()) {
				sep = "";

				for (int i = 1; i <= numberOfColumns; i++) {
					System.out.print(sep);
					System.out.print("" + rs.getObject(i));
					sep = ",";
				}

				out.write(LINEFEED);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) { /* ignore */
			}
		}
	}

Open in new window

Author

Commented:
Thanks for the prompt suggestions.I tried both ways.they are working good for me.

Output is like this in csv
event count

event1  0
event2 3

is there anyway that i could color the first two columns in the first row.I mean how to color in csv for particular rows and columns
Awarded 2011
Awarded 2011

Commented:
I don't think you can color in the csv file.
For that you may want to go to Excel file say using POI - which will take much more work, but it can use
many finctions of Excel.
CSV is just plain text format - so I'm really not sure about the color - you can probably have some sophisticated editor which can read csv and color the headers,
but csv by itself is not concerned with formatting etc - it is just plain text

Author

Commented:
Thank You Yan for the suggestions

Author

Commented:
Yan I need to manipulate the Csv i get to xml .How can i do with the Xstream?
Awarded 2011
Awarded 2011

Commented:
Create an object with fields say EventName Eventvalue
and each time you get to two values - when youy are redy to write the line
in CSV in the code above create new instance of such object
 EventObject eo = new EventObject(evetntname, eventvalue);
String xml = xstream.toXML(eo);
like in this example:

http://xstream.codehaus.org/tutorial.html

(section serializing object to XML)

Something of this sort should work


Author

Commented:
I have got the xml ouptut as attached.
out.txt

Author

Commented:

                  
                XStream xstream = new XStream();
                String xml = xstream.toXML(map3);
                System.out.println("xml..."+xml);
the above  code gives the xml  as attached file


I am trying to change the elements name .is there anyway to do it?Thanks in advance

Author

Commented:
i am getting the event and count values as hash map
Awarded 2011
Awarded 2011

Commented:
Don't understand what you mean by "attached file" ?
What is map3 and how do you create it?

Author

Commented:
     while(resultSet.next()){
                        String event = resultSet.getString("EVENTTYPE");
                        int countEvent = resultSet.getInt("COUNTS");
                        map1.put(event,countEvent );
                  }
                  
                  map3.putAll(map1);

this is how i created map3.attached file is the xml output,i have put in a txt file and attached it.sorry for confusion
Awarded 2011
Awarded 2011

Commented:
Which elemen names you want to change - "string" and "int" ?

Author

Commented:
i want to change both the elements as String--EventType and int --Count
Awarded 2011
Awarded 2011

Commented:
look at that example more closely:
http://xstream.codehaus.org/tutorial.html

I am guessing the if you come up with some class
like EventInfo and it would have two fields String EventType and
int count and you will make ArrayList made up of the objects of
such class XStream will produce something similar with what you see in example
in the above link and your elements will be named EventType and count

Author

Commented:
Thanks Yan it worked out.I have a small concern that is there anyway to convert print stream to string?
Awarded 2011
Awarded 2011

Commented:

Author

Commented:
I tried that but not sure how to get it as string.I need to send as to another method as String
Awarded 2011
Awarded 2011

Commented:

I think this is how you get String from PrintStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println(//do your printing here);

String content = baos.toString(charsetName);

Open in new window

Author

Commented:
it worked out previously i am giving wrong encoding.Thanks once again

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println(//do your printing here);

String content = baos.toString("UTF-8");
Awarded 2011
Awarded 2011

Commented:
Great!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial