-1

I have CSV file to read , and i am storing in string and i need to split string at every "," and my input will be like

Name, Id, Description, emailId Micheal,234655,"Test description for the next line issue Thanks and Regards,Mike",Mike@yahoo.com

Kindly help me with this.

Regards, Vijay

enter code here

import java.io.*;
import java.util.logging.*;
import java.util.ArrayList;
import java.util.List;
public class ReadingCSVFile {

 public static void main(String args[])
 {
    StringBuilder sb =new StringBuilder();
    int n;
    String inputStream;
    String Name[] =new String[30];
    List l1 = new ArrayList();
    try
    {
         FileInputStream fis =new  fileInputStream("C:/Users/vijaykumar.naga/Desktop/Abc.txt"); 
     FileOutputStream fos = new FileOutputStream("C:/Users/vijaykumar.naga/Desktop/Output.txt");
     int ch;
     while((ch = fis.read()) != -1){
         sb.append((char)ch);
     }
     System.out.println("The InputString is " +sb.toString());
     String abcd =sb.toString();
       for(int i=0; i<30; i++)
         {
         l1.add(abcd.split(","));
         System.out.println("The Names are " +l1);
          }

        }
    catch(Exception e)
     {

      }
    }

  }
Vijay
  • 9
  • 3
  • 2
    What's the problem with the current approach – Bálint Oct 25 '16 at 10:49
  • Use StringTokenizer to https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html – kedar kamthe Oct 25 '16 at 10:50
  • So you read all the file, appending a Stringbuilder. then you split the full result by the `,` 30 time, and add the same String[] values (not samee reference) into the list. Not sure you did what you expected – AxelH Oct 25 '16 at 11:00
  • How many line the file contains, one or more ? EDIT : I just post my home made (basic) parser. Using a Scanner to read a multiline file – AxelH Oct 25 '16 at 11:14
  • Possible duplicate of [CSV parsing in Java - working example..?](http://stackoverflow.com/questions/843997/csv-parsing-in-java-working-example) – Konstantin Labun Oct 25 '16 at 12:28

4 Answers4

0

Please see the revision of your code with an explanation :

import java.io.*;
import java.util.logging.*;
import java.util.ArrayList;
import java.util.List;
public class ReadingCSVFile {

 public static void main(String args[])
 {
    StringBuilder sb =new StringBuilder();
    int n;
    String inputStream;
    String Name[] =new String[30];
    List<String> l1 = new ArrayList<>(); //Use generics <> operator
    try
    {
         FileInputStream fis =new  fileInputStream("C:/Users/vijaykumar.naga/Desktop/Abc.txt"); 
     FileOutputStream fos = new FileOutputStream("C:/Users/vijaykumar.naga/Desktop/Output.txt");
     int ch;
     while((ch = fis.read()) != -1){
         sb.append((char)ch);
     }
     System.out.println("The InputString is " +sb.toString());
     String abcd =sb.toString();
       /*for(int i=0; i<30; i++)
         {
         l1.add(abcd.split(","));           //This is wrong. abcd.split(",") will return String[]
         System.out.println("The Names are " +l1);
          }

        }*****This loop is not needed*/ 
    //As you already read the content in abcd variable, do as follows
    l1.addAll(Arrays.asList(abcd.split(",")));

    catch(Exception e)
     {

      }
    }

  }
Chirag Parmar
  • 833
  • 11
  • 26
  • He needs to store in array..not in list – Karthik Oct 25 '16 at 11:02
  • But if he would store the line as a String[] into his List (like in the original), you change a bit more here ;) – AxelH Oct 25 '16 at 11:02
  • @Karthik, If you know the number of line not a problem but it is better to use an List. At the end, use the methods toArray if you need. I guess the OP prefer this approach – AxelH Oct 25 '16 at 11:04
  • Yeah exactly.. I agree with @AxelH..If you have the list, you can convert it into an array and in this context, List is more preferable to use. – Chirag Parmar Oct 25 '16 at 11:05
0

This is a simple solution I use to read a CSV file.

    Scanner sc = null;
    try {
        sc = new Scanner(new File("test.csv"));
        String s = null;
        String[] array;
        while(sc.hasNext()){
            s = sc.nextLine();
            array = s.split(",");
            System.out.println(Arrays.toString(array));
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } finally {
        if(sc != null) sc.close();
    }

Basicly, this will use a Scanner to read one line at a time, probably not the best but for 40 lines, I don't really care ;)

Then, I split the line using the comma, careful if , is used in the values, no check are made here.

Then, I print the array in the console.

EDIT :

try (Scanner sc = new Scanner(new File("test.csv"))){
        String s = null;
        String[] array;
        while(sc.hasNext()){
            s = sc.nextLine();
            array = s.split(",");
            // Do what you want with the array, here I just print the result
            System.out.println(Arrays.toString(array));
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
AxelH
  • 14,325
  • 2
  • 25
  • 55
  • 5 Years since Java has try-with-resources and some people still use the ordinary `try/catch` idiom for reading files? – Tom Oct 25 '16 at 11:19
  • @Tom Simple reason, at the office there are still on JAVA 6 ! :( But you are right, I will edit this, could you validate it, just in case I – AxelH Oct 25 '16 at 11:23
  • @Tom, also, I could have use a Stream API for this, but again, can't test this here. And 5Years ? The first release has 2 years no ? – AxelH Oct 25 '16 at 11:25
  • 1
    You're talking about Java 8, but try-with-resources was introduced in Java 7. Btw you don't need to split the file instantiation from the Scanner. So `try(Scanner sc = new Scanner(new File("test.csv"))` would be fine. *"Simple reason, at the office there are still on JAVA 6"* That's pretty sad. Really. Java 6 is way too old to still work with it. – Tom Oct 25 '16 at 11:27
  • 1
    @Tom Yes, you are right again, I mixed my version here, but again, Java 6 :( that's painful, I even start to forgot to use those when I can. Just for the history, this is a Bank using JCAPS, Banks have difficulties to update their technilogy... PS : You are welcome to edit my answer you know. No hard feelings here. – AxelH Oct 25 '16 at 11:30
0

I would suggest to use a regex like:

([A-Za-z]+)\,(\d+)\,(\".+\"|.+)\,(\w+@\w+\.\w+)
David Buck
  • 3,752
  • 35
  • 31
  • 35
blubber
  • 11
  • 1
-1

You can try split()

Use below syntax

String[] parts = string.split(",");

Or you can use StringTokenizer with token as ,

Hope this helps

Kedar1442
  • 217
  • 2
  • 8