Results 1 to 9 of 9
  1. #1
    jls7884 is offline Member
    Join Date
    Nov 2016
    Posts
    22
    Rep Power
    0

    Default Reading data from a CSV file in java

    I need to declare a getList method as follows:
    Method getList:
    Note that the method getList is underlined. Underlining a
    method in a UML class diagrams indicates that the
    method is static.
    The method getList should readin the data from the csv
    file book.csv. If a line doesn’t follow the pattern
    title,author,yearthen a message should be written
    to the standard error stream (see sample output) The
    program should continue reading in the next line. NO
    exception should be thrown .

    I have never read from a CSV file before and had no idea how to go about this. After some researching online I came up with this code:
    Java Code:
    public static void getList() {
            String fileName = "books.csv";
            File file = new File("C:\\Users\\Jacob\\Documents\\NetBeansProjects\\Books\\src\\Books\\books.csv"); 
            
            try {
                try (Scanner inputStream = new Scanner(file)) {
                    while (inputStream.hasNext()){
                        String data = inputStream.next();
                        System.out.println(data);
                    }
                }
            } catch (FileNotFoundException e){
            }
        }
    First problem is that according to the guidelines I am not to throw an exception though I cannot use this method without the FileNotFoundException. Secondly my code does not seem to output anything: [title=null, author=null, year=0]

    Any ideas on how I should modify this code or do I need to go about it a completely different way?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Reading data from a CSV file in java

    A method with name starting with get should return something. I don't see where that is discussed in the description.
    What should the getList() method return?
    Should the values on each line in the file be separated from the values on another line?
    For example, if the file has these lines:
    a,b,c
    d,e
    What should be returned?

    What character separates the fields in the CSV file? Often it is a comma but could be some other character.
    The Scanner class can be set to use any desired character for a field value delimiter.

    NO exception should be thrown .
    What should the method do if there is an exception?
    Catch any exception, Show a message and return a null value?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jls7884 is offline Member
    Join Date
    Nov 2016
    Posts
    22
    Rep Power
    0

    Default Re: Reading data from a CSV file in java

    The method is very confusing to me as all it says is it reads the csv file. I would assume that I somehow need get the values in the file using my get methods for title, author, and year just unsure how to go about it. Is there a way I can post a pdf? It might help to be able to see the whole thing instead of just that one part. The data in the file is separated by commas. In my test app I will be printing the number of books read in and sort the list in natural order and reverse order and print those lists.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Reading data from a CSV file in java

    I don't have anything new to say.
    A method named get should return a value.

    data in the file is separated by commas.
    The Scanner class can be set to use a comma for a delimiter.

    Start by writing code to read the file, get the tokens and print them.

    Later you will need to decide what to do with the data that was read.

    The method is very confusing to me
    Maybe you should ask your instructor about that.
    Last edited by Norm; 01-21-2017 at 10:06 PM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    jls7884 is offline Member
    Join Date
    Nov 2016
    Posts
    22
    Rep Power
    0

    Default Re: Reading data from a CSV file in java

    I would ask my instructor if I could. This was assigned as a review assignment on Thursday and is due today but I have never done anything close to it the past. I have no idea how to read a cvs file. On another note maybe I don't understand the uml diagram. Haven't had much experience with them. Here is getList: +getList (file : String) : List<Book>

    Does this mean my method getList is static and of type String with String file as the parameter and it will return an arraylist Book containing the values from the cvs file?
    Last edited by jls7884; 01-21-2017 at 10:39 PM.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Reading data from a CSV file in java

    how to read a csv file
    Use the Scanner class's methods.
    You need a definition of what is in the file.
    Are there lines?
    do the lines have values?


    +getList (file : String) : List<Book>
    Sorry I'm not familiar with that notation.
    Does this mean my method getList is static and of type String with String file as the parameter and it will return an arraylist Book containing the values from the cvs file?
    That makes sense.
    My guess is that the getList() method takes a String as arg and returns a List of Book objects.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    jls7884 is offline Member
    Join Date
    Nov 2016
    Posts
    22
    Rep Power
    0

    Default Re: Reading data from a CSV file in java

    I am now using this csvhelper class:

    Java Code:
    /*
     * Copyright 2013 Keith D Swenson
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *    http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package org.workcast.streams;
    
    import java.io.Reader;
    import java.io.Writer;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Helps to read and write a CSV file, all methods are static writeLine:
     * Converts list of String values into a line of a CSV file parseLine: read a
     * line from a LineNumberReader and return the list of Strings
     *
     * That should be all you need. Create or open the file & streams yourself from
     * whatever source you need to read from.. Everything in this class works on
     * characters, and not bytes.
     */
    public class CSVHelper {
    
        public static void writeLine(Writer w, List<String> values) throws Exception {
            boolean firstVal = true;
            for (String val : values) {
                if (!firstVal) {
                    w.write(",");
                }
                w.write("\"");
                for (int i = 0; i < val.length(); i++) {
                    char ch = val.charAt(i);
                    if (ch == '\"') {
                        w.write("\""); // extra quote
                    }
                    w.write(ch);
                }
                w.write("\"");
                firstVal = false;
            }
            w.write("\n");
        }
    
    
        /**
        * returns a row of values as a list
        * returns null if you are past the end of the line
        */
        public static List<String> parseLine(Reader r) throws Exception {
            int ch = r.read();
            while (ch == '\r') {
                //ignore linefeed characters wherever they are, particularly just before end of file
                ch = r.read();
            }
            if (ch<0) {
                return null;
            }
            ArrayList<String> store = new ArrayList<String>();
            StringBuffer curVal = new StringBuffer();
            boolean inquotes = false;
            boolean started = false;
            while (ch>=0) {
                if (inquotes) {
                    started=true;
                    if (ch == '\"') {
                        inquotes = false;
                    }
                    else {
                        curVal.append((char)ch);
                    }
                }
                else {
                    if (ch == '\"') {
                        inquotes = true;
                        if (started) {
                            // if this is the second quote in a value, add a quote
                            // this is for the double quote in the middle of a value
                            curVal.append('\"');
                        }
                    }
                    else if (ch == ',') {
                        store.add(curVal.toString());
                        curVal = new StringBuffer();
                        started = false;
                    }
                    else if (ch == '\r') {
                        //ignore LF characters
                    }
                    else if (ch == '\n') {
                        //end of a line, break out
                        break;
                    }
                    else {
                        curVal.append((char)ch);
                    }
                }
                ch = r.read();
            }
            store.add(curVal.toString());
            return store;
        }
    }
    Here is my new code to read the data though it still returns null:

    Java Code:
    public static Book toString (List<String> values) {
           String _title = values.get(0);
           String _author = values.get(1);
           int _year = Integer.parseInt(values.get(2));
           return new Book(_title, _author, _year);
        }
        
        public List<String> getValues() {
            Vector<String> values = new Vector<> ();
            values.add(title);
            values.add(author);
            values.add(Integer.toString(year));
            return values;
        }
        
        public static List<Book> getList() throws Exception {
        List<Book> collection = new Vector<>();
        File csvFile = new File("C:\\Users\\Jacob\\Documents\\NetBeansProjects\\Books\\src\\Books\\books.csv");
        FileInputStream fis = new FileInputStream(csvFile);
        Reader fr = new InputStreamReader(fis, "UTF-8");
     
        List<String> values = CSVHelper.parseLine(fr);
        while (values!= null) {
            collection.add( Book.toString(values));
            values = CSVHelper.parseLine(fr);
        }
        fis.close();
        return collection;
        }
    I would think this works. Any errors you can see?

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Reading data from a CSV file in java

    it still returns null:
    Please copy the full text of the error message and paste it here. It has important info about the error.
    Last edited by Norm; 01-22-2017 at 02:10 AM.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    jls7884 is offline Member
    Join Date
    Nov 2016
    Posts
    22
    Rep Power
    0

    Default Re: Reading data from a CSV file in java

    I don't have any error message. It compiles and runs fine. I created print statements for title, author and year. Those are what return null.

Similar Threads

  1. Replies: 8
    Last Post: 02-08-2015, 06:11 AM
  2. Replies: 1
    Last Post: 02-09-2014, 12:41 AM
  3. Replies: 11
    Last Post: 04-27-2012, 07:43 PM
  4. Reading data from file
    By Roberto1989 in forum New To Java
    Replies: 1
    Last Post: 04-28-2011, 05:52 PM
  5. Replies: 0
    Last Post: 11-24-2009, 01:49 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •