1

Hello I'm a newbie in Java using BlueJ. I have a csv file that contains a load of data in a table arrangement. I'm trying to find a way to take this information and find out how many comma separated values there are in the first row then regardless of rows put each comma separated value into an array.

Does anyone have any advice on how to do this?

Thanks in advance,
Harry.

5
  • 2
    what have you tried? Commented Nov 22, 2012 at 18:11
  • I can't try anything as I don't know the code required to put even just a string into an array. Commented Nov 22, 2012 at 18:21
  • String[] foo = new String[1]; foo[0] = "bar"; this is basic Java. Commented Nov 22, 2012 at 18:22
  • Sorry, I'm a self taught begginer and some things are a bit patchy. Commented Nov 22, 2012 at 18:27
  • i know, but copying code from answers might get your ideas working, but you'll never learn java. Try a book or an online course, as Strings and arrays are the absolute necessary basics to understand. I wouldn't start learning Java by parsing csv files. Commented Nov 22, 2012 at 18:29

3 Answers 3

2

CSV parsing can be tricky because of the need to support quoted values. I suggest not writing your own CSV parser, but using an existing library such as http://opencsv.sourceforge.net/.

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

4 Comments

There didn't seem to be any anything on arrays in the website, thanks anyway.
@user1843403 Funny you should say that, since I found it within 5 seconds. The very first topic under the section "Reading and Writing".
Oh, I thought the section on reading and writing would just be accessing it and writing to a csv, not accessing it and writing into java. But it only shows how to put each line into an array, not each value. It did have something useful about how to skip reading the first row so that's good, thanks.
@user1843403 You misunderstand. Each line (CSV record) is parsed into a String[], each array element being one CSV value (field).
0

You can use the Scanner file, to read each line of the file, something similar to:

//  create a File object by giving the filepath
File file = new File("C:\\data.csv");

try {
    // Create a new scanner class that will read the file
    Scanner scanner = new Scanner(file);

    //  while the file has lines to read
    while (scanner.hasNextLine()) {

        //  read the line to a string
        String line = scanner.nextLine();

        //  do what you need with that line
    }
//  catch the exception if no file can be found
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Comments

0

Here is another library to handle csv file. javacsv Code example is here

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.