Hackerss.com

hackerss
hackerss

Posted on

Read a csv file in Java

Read a csv file - Java:


import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ReadCSV {
   /**
   * This method read a csv file.
   * @param fileName name of the file to read.
   * @return List<String> Obtains the list of lines of the file.
   */   
   public List<String> readCSV(String fileName) {
       //Variable to store the lines of the file
       List<String> lines = new ArrayList<String>();
       //Try to read the file
       try {
           //Create a BufferedReader to read the file
           BufferedReader br = new BufferedReader(new FileReader(fileName));
           //Read the lines of the file
           String line = br.readLine();
           while (line != null) {
               //Add the line to the list of lines
               lines.add(line);
               //Read the next line
               line = br.readLine();
           }
           //Close the BufferedReader
           br.close();
       } catch (IOException e) {
           //Print an error message if an error occurs
           System.out.println("Error reading file " + fileName);
       }
       //Return the list of lines of the file
       return lines;
   }

   /**
   * One Example
   */
   public static void main(String args[]) throws IOException {

      ReadCSV  readCSV= new ReadCSV ();
      //Example
      List<String> lines = readCSV.readCSV("example.csv");

      //Output
      for (String line : lines) {
         System.out.println(line); //"1,2,3" "4,5,6" "7,8,9" ...
      }

   }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)