#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2011
    Posts
    2
    Rep Power
    0

    Java CSV reader/writer advice?


    I am currently working on a simple .csv reader/writer class for an app that I am building and would like some advice or input. The current code seems to work well but I am fairly new to using external files with my programs so I'd like to hear if there is any newer or more efficient way to do this than what I have posted or if there are any major flaws that I have missed.
    Thanks.

    Code:
    import java.io.*;
    import java.util.ArrayList;
    public class CSVData {
    	public ArrayList<String[]> readCSV(String filename) throws Exception {
    		BufferedReader reader = new BufferedReader(new FileReader(filename));
    		ArrayList<String[]> rows = new ArrayList<String[]>();
    		String line = reader.readLine();
    		while(line != null) {
    			String[] row = line.split(",");
    			for (int x = 0; x<row.length; x++) {
    				row[x] = row[x].trim(); 
    			}
    			rows.add(row);
    			line = reader.readLine();
    		}
    		return rows;
    	}
    	public void writeCSV(ArrayList<String[]> data, String filename) throws Exception {
    		FileWriter writer = new FileWriter(filename);
    		for (int x = 0; x < data.size(); x++) {
    			String[] line = data.get(x);
    			for (int y = 0; y < line.length; y++) {
    				if (y < line.length-1) {
    					writer.append(line[y]+",\t");
    				} else {
    					writer.append(line[y]);
    				}
    			}
    			writer.append("\n");
    		}
    		writer.flush();
    		writer.close();
    	}
    }
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    15
    Looks good to me.

    It is generally a good idea to close any file access in a 'finally' block. That way, if an exception gets thrown when reading or writing, the file gets freed up before the exception propagates. Here is an example.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    1
    Rep Power
    0
    Hey Darkoasis,
    I tried reading a .csv file with your code and set up a counter. At the end of reading, counter was 49628 but actual number of rows in the .csv file are 49524.

    Can you please help me ? whats wrong would I may be doing ?

IMN logo majestic logo threadwatch logo seochat tools logo