[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 489
  • Last Modified:

to create a csv file

Hello Experts,
The code iam using is

public static void main(String [] args)throws Exception {
     Vector v= new Vector();
     String fileName="C:/exp.csv";
     FileOutputStream out=new FileOutputStream(fileName);
     StringBuffer s = new StringBuffer();
     PrintWriter pw= new PrintWriter(out);
          for (int i=0;i<v.size();i++){
            String str=(String)v.elementAt(i);
            String strs[]=str.split(" ");
            for (int j=0; j<strs.length;j++)
          {
              s.append(strs[j]);
              if (j<strs.length-1) s.append(",");
          }
           
          }
            pw.write(s.toString());
               

      pw.flush();
      pw.close();
 }

My vector consists of objects like
"Mon Aug 11 20:00:00 CEST 2004 A 2.459 "
"Mon Aug 11 20:00:00 CEST 2005 A 2.459 "
if I Use String strs[]=str.split(" "); and  s.append(","); My csv file is like
Mon, Aug, 11, 20:00:00, CEST, 2004 ,A,2.459 Mon, Aug, 11, 20:00:00, CEST, 2005, A. 2.459.
But it should be like
 Mon Aug 11 20:00:00 CEST 2004 ,A,2.459
 Mon Aug 11 20:00:00 CEST 2005 ,A,2.459

Thanks
0
vihar123
Asked:
vihar123
  • 15
  • 14
  • 3
  • +3
1 Solution
 
CEHJCommented:
You need to count the tokens and only append a separator after the required number of tokens has been reached
0
 
CEHJCommented:
if (i == 5 || i == 6) {
       s.append(',');
}
0
 
CEHJCommented:
Or rather:

if (j == 5 || j == 6) {
     s.append(',');
}
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
vihar123Author Commented:
how to append "," to the next values
0
 
vihar123Author Commented:
"Mon Aug 11 20:00:00 CEST 2003 A 2.459 1.5139 0.87233 0.325 0.10054";
0
 
vihar123Author Commented:
Ok,
if(j>=5)
s.append(',');

0
 
NievergeltCommented:
CEHJ is almost there:

public static void main(String [] args)throws Exception {
     Vector v= new Vector();
     String fileName="C:/exp.csv";
     FileOutputStream out=new FileOutputStream(fileName);
     StringBuffer s = new StringBuffer();
     PrintWriter pw= new PrintWriter(out);
          for (int i=0;i<v.size();i++){
            String str=(String)v.elementAt(i);
            String strs[]=str.split(" ");
            for (int j=0; j<strs.length; j++)
          {
              s.append(strs[j]);
              if ((j < strs.length-1) && (j >= 5) {
                s.append(",");
              }
          }
           
          }
            pw.write(s.toString());
               

      pw.flush();
      pw.close();
 }
0
 
vihar123Author Commented:
MonAug1120:00:00CEST2004 ,A,2.459 MonAug 11 20:00:00CEST2005, A,2.459.

But it should be like
 Mon Aug 11 20:00:00 CEST 2004 ,A,2.459
 Mon Aug 11 20:00:00 CEST 2005 ,A,2.459
0
 
NievergeltCommented:
Yes, you are right, but tht did not work before, either ;-).

public static void main(String [] args)throws Exception {
     Vector v= new Vector();
     String fileName="C:/exp.csv";
     FileOutputStream out=new FileOutputStream(fileName);
     StringBuffer s = new StringBuffer();
     PrintWriter pw= new PrintWriter(out);
          for (int i=0;i<v.size();i++){
            String str=(String)v.elementAt(i);
            String strs[]=str.split(" ");
            for (int j=0; j<strs.length; j++)
          {
              s.append(strs[j]);
              if (j < strs.length-1) {
                if (j >= 5)
                  s.append(",");
              }
              else
                s.append("\r\n");  // "\n" for Unix and "\r" for Macintosh (unless they changed that in OS X)
          }
           
          }
            pw.write(s.toString());

      pw.flush();
      pw.close();
 }
0
 
CEHJCommented:
Using the code i posted:

                  for(int i = 0;i < tokens.length;i++) {
                        s.append(tokens[i]);
                        if (i == 5 || i == 6) {
                              s.append(',');
                        }
                        else if (i < tokens.length - 1) {
                              s.append(' ');
                        }
                  }


Gives the output

Mon Aug 11 20:00:00 CEST 2004,A,2.459

which is what you want isn't it?
0
 
objectsCommented:
You just need to add a newline after processing each entry
Also a lot easier to output each line as you are processing:

public static void main(String [] args)throws Exception {
     Vector v= new Vector();
     String fileName="C:/exp.csv";
     FileOutputStream out=new FileOutputStream(fileName);
     PrintWriter pw= new PrintWriter(out);
     for (int i=0;i<v.size();i++){
       StringBuffer s = new StringBuffer();
       String str=(String)v.elementAt(i);
       String strs[]=str.split(" ");
       for (int j=0; j<strs.length;j++)
       {
          s.append(strs[j]);
          if (j<strs.length-1) s.append(",");
       }    
       pw.println(s.toString());
     }
     pw.flush();
     pw.close();
 }

0
 
vihar123Author Commented:
Sorry ,The object in vector is like
Tue Dec 05 20:00:00 CET 2000
A
2.4554
1.7368
0.77792
0.50038
0.21094
0.07494
-0.02261
-0.05206
-0.01164
7.9326

Now how to append "," and that should be in one line like
Tue Dec 05 20:00:00 CET 2000,A,2.4554,1.7368,0.77792 ,0.50038 ,0.21094 ,0.07494 ,-0.02261 ,-0.05206
0
 
CEHJCommented:
Can you please say whether the following:

>>Mon Aug 11 20:00:00 CEST 2004,A,2.459

*is* the format you want vihar123, since you seemed to suggest this earlier
0
 
mightyoneCommented:
lol forget about the split....

public static void main(String [] args)throws Exception {
     Vector v= new Vector();
     String fileName="C:/exp.csv";
     FileOutputStream out=new FileOutputStream(fileName);
     PrintWriter pw= new PrintWriter(out);
     for (int i=0;i<v.size();i++){
       StringBuffer s = new StringBuffer();
       s.add((String)v.elementAt(i));
       s.append(",");
       }    
       pw.println(s.toString());
     }
     pw.flush();
     pw.close();
 }
0
 
mightyoneCommented:
s.add((String)v.elementAt(i));

must be

s.append((String)v.elementAt(i));
0
 
vihar123Author Commented:
One more Dought is ,The object in vector is like
Tue Dec 05 20:00:00 CET 2000  // date
A
2.4554
1.7368
0.77792
0.50038
.. like some values
Tue Dec 05 20:00:00 CET 2000  // again date and some values
A
2.4554
..
The Csv file should be like start with date and some values , if again date comes then it should be in the next line .
0
 
vihar123Author Commented:
Sorry CEHJ ,
Thanks for your help and i will give you some points :)
0
 
vihar123Author Commented:
I Have increased the points .
0
 
objectsCommented:
When you come across a date field make the println() call to print out the previous line.
If the number of columns is defined then you could also use an inner loop when reading thru your vector
ie. read next n elements of vector and output to a line, read next n etc
0
 
limaidealCommented:
change

for (int j=0; j<strs.length;j++)
          {
              s.append(strs[j]);
              if (j<strs.length-1) s.append(",");
          }
           
          }

to:

for (int j=0; j<strs.length;j++)
          {
              s.append(strs[j]);
              if (j<strs.length-1) s.append(",");
          }
          s.append(System.getProperty("line.separator"));
          }
0
 
limaidealCommented:
Actually sometime, exporting a CSV file could be more complicated than that. For example, if your content has ',', you need to put quote '"' signe around string items. Then if you already have " sign in content, you need to escape it to double quote.

 
0
 
CEHJCommented:
>>s.append(System.getProperty("line.separator"));

That's not necessary - a PrintWriter is being used
0
 
vihar123Author Commented:
Iam using this code to create a csv file
public static void main(String [] args)throws Exception {
     Vector v= new Vector();
     String fileName="C:/exp.csv";
     FileOutputStream out=new FileOutputStream(fileName);
     PrintWriter pw= new PrintWriter(out);
     for (int i=0;i<v.size();i++){
       StringBuffer s = new StringBuffer();
       s.add((String)v.elementAt(i));
       s.append(",");
       }    
       pw.println(s.toString());
     }
     pw.flush();
     pw.close();
 }

The object in vector is like
Tue Dec 05 20:00:00 CET 2000  // date
A
2.4554
1.7368
0.77792
0.50038
.. like some values
Tue Dec 05 20:00:00 CET 2000  // again date and some values
A
2.4554
..
The Csv starts with date and some values , if again date comes then it should be in the next line .
Can you give me the code please ?
0
 
CEHJCommented:
>>The object in vector is like

In your code the Vector is empty
0
 
vihar123Author Commented:
>> Vector v= new Vector(); don't consider this .
I have added some data to vector.
Data in my vector is like
Tue Dec 05 20:00:00 CET 2000  // date
A
2.4554
1.7368
0.77792
0.50038
...

 Tue Dec 05 20:00:00 CET 2000  // again date and some values
A
2.4554
0.77792
0.50038
..
Tue Dec 05 20:00:00 CET 2000  // again date and some values
...
0
 
CEHJCommented:
OK. If those are Strings then you can ignore the business of counting tokens. Just append a comma each time the token is written
0
 
vihar123Author Commented:
StringBuffer s = new StringBuffer();
       s.add((String)v.elementAt(i));
       s.append(",");
       }    
       pw.println(s.toString());
This code appends comma , but the csv file is like
Tue Dec 05 20:00:00 CET 2000 , 2.4554,1.7368 ,Tue Dec 05 20:00:00 CET 2000 , 2.4554,1.7368 ,..........
2.4554,1.7368 ,Tue Dec 05 20:00:00 CET 2000 , 2.4554,1.7368 ,..........,1.7368 ,

But i want it ,should be like
Tue Dec 05 20:00:00 CET 2000 , 2.4554,1.7368
Tue Dec 05 20:00:00 CET 2000 , 2.4554,1.7368
Every row should start with date and there should not be a comma at the end of the row.

Thanks
0
 
CEHJCommented:
If your vector contains just those Strings (defining the obvious constant appropriately):


            for (int i = 0; i < v.size(); i++) {
                  if (i != 0 && i % (NUMBER_OF_TOKENS_SEPARATING_EACH_DATE + 1) == 0) {
                        pw.println();
                  } else if (i != 0){
                        pw.print(",");
                  }
                  pw.print((String) v.get(i));
            }
0
 
vihar123Author Commented:
The values should be " Float " data type .
0
 
CEHJCommented:
pw.print("" + v.get(i));
0
 
vihar123Author Commented:

NUMBER_OF_TOKENS_SEPARATING_EACH_DATE  are not same for all rows :)
0
 
CEHJCommented:
You need to tell us all this sort of thing first - otherwise we'll be wasting our time
0
 
vihar123Author Commented:
Ok ,  Sorry ........Leave it i will check once again.
Thanks for your help.
0
 
objectsCommented:
And thats all been previously stated already anyway :)

If you don't know when a date will appear then you'll need to parse the token (as if it was a Date).
If it parses ok it is a date and you can add a new line, otherwise it isn't.
0
 
CEHJCommented:
>>And thats all been previously stated already anyway :)

Where?
0
 
CEHJCommented:
>>NUMBER_OF_TOKENS_SEPARATING_EACH_DATE  are not same for all rows :)

In any case, vihar123, this is not how CSV files work. They represent data in tabular form, i.e. in a given, *regular* number of columns. If any of the cells in the row is empty, there still has to be a delimiter to show to the parser that it is.
0
 
vihar123Author Commented:
Hi CEHJ,
Thanks a lot for your great help.
0
 
CEHJCommented:
:-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 15
  • 14
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now