Link to home
Start Free TrialLog in
Avatar of googleart
googleart

asked on

how to write String values to csv file in java

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
Avatar of for_yan
for_yan
Flag of United States of America image

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

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

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



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

Avatar of CEHJ
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

Avatar of googleart
googleart

ASKER

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
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
Thank You Yan for the suggestions
Yan I need to manipulate the Csv i get to xml .How can i do with the Xstream?
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


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

                  
                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
i am getting the event and count values as hash map
Don't understand what you mean by "attached file" ?
What is map3 and how do you create it?
     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
Which elemen names you want to change - "string" and "int" ?
i want to change both the elements as String--EventType and int --Count
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
Thanks Yan it worked out.I have a small concern that is there anyway to convert print stream to string?
I tried that but not sure how to get it as string.I need to send as to another method as String

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

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");
Great!