Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, March 19, 2016

Read one line of a csv file in Java

Read one line of a csv file in Java


I have a csv file that currently has 20 lines of data. The data contains employee info and is in the following format:

first name, last name, Employee ID

So one line would like this: Emma, Nolan, 2

I know how to write to the file in java and have all 20 lines print to the console, but what I'm not sure how to do is how to get Java to print one specific line to the console.

I also want to take the last employee id number in the last entry and have java add 1 to it one I add new employees. I thinking this needs to be done with a counter just not sure how.

Answer by micha for Read one line of a csv file in Java


You can do something like this:

BufferedReader reader = new BufferedReader(new FileReader(<>));  List lines = new ArrayList<>();  String line = null;  while ((line = reader.readLine()) != null) {      lines.add(line);  }    System.out.println(lines.get(0));  

With BufferedReader you are able to read lines directly. This example reads the file line by line and stores the lines in an array list. You can access the lines after that by using lines.get(lineNumber).

Answer by Caffe Latte for Read one line of a csv file in Java


BufferedReader reader =new BufferedReader(new FileReader("yourfile.csv"));            String line = "";          while((line=reader.readLine())!=null){              String [] employee =line.trim().split(",");              // if you want to check either it contains some name              //index 0 is first name, index 1 is last name, index 2 is ID          }  

Answer by R Dub for Read one line of a csv file in Java


You can read text from a file one line at a time and then do whatever you want to with that line, print it, compare it, etc...

// Construct a BufferedReader object from the input file  BufferedReader r = new BufferedReader(new FileReader("employeeData.txt"));  int i = 1;  try {        // "Prime" the while loop              String line = r.readLine();      while (line != null) {            // Print a single line of input file to console          System.out.print("Line "+i+": "+line);             // Prepare for next loop iteration          line = r.readLine();          i++;      }  } finally {      // Free up file descriptor resources      r.close();  }    // Remember
the next available employee number in a one-up scheme int nextEmployeeId = i;

Answer by RichyRich for Read one line of a csv file in Java


Alternatively, If you want more control over read CSV files then u can think about CsvBeanReader that will give you more access over files contents..

Answer by George T 97 for Read one line of a csv file in Java


Here is an algorithm which I use for reading csv files. The most effective way is to read all the data in the csv file into a 2D array first. It just makes it a lot more flexible to manipulate the data.

That way you can specify which line of the file to print to the console by specifying it in the index of the array and using a for. I.e: System.out.println(employee_Data[1][y]); for record 1. y is the index variable for fields. You would need to use a For Loop of course, to print every element for each line.

By the way, if you want to use the employee data in a larger program, in which it may for example store the data in a database or write to another file, I'd recommend encapsulating this entire code block into a function named Read_CSV_File(), which will return a 2D String array.

My Code

// The return type of this function is a String.   // The CSVFile_path can be for example "employeeData.csv".   public static String[][] Read_CSV_File(String CSVFile_path){        String employee_Data[][];  int x;  int y;  int noofFields;  try{      String line;      BufferedReader in = new BufferedReader(new FileReader(CSVFile_path));         // reading files in specified directory        // This assigns the data to the 2D array       // The program keeps looping through until the line read in by the console contains no data in it i.e. the end of the file.       while ( (( line = in.readLine()) != null ){          String[] current_Record = line.split(",");          if(x == 0) {              // Counts the number of fields in the csv file.               noofFields = current_Record.length();            }          for (String str : values) {              employee_Data[x][y] = str;              System.out.print(", "+employee_Data[x][y]);              // The field index variable, y is incremented in every loop.               y = y + 1;            }          // The record index variable, x is incremented in every loop.           x = x + 1;        }          // This frees up the BufferedReader file descriptor resources           in.close();      /*  If an error occurs, it is caught by the catch statement and an error message       *   is generated and displayed to the user.       */  }catch( IOException ioException ) {      System.out.println("Exception: "+ioException);  }  // This prints to console the specific line of your choice       System.out.println(("Employee 1:);      for(y = 0; y < noofFields ; y++){          // Prints out all fields of record 1           System.out.print(employee_Data[1][y]+", ");      }  return employee_Data;              }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Related Posts:

0 comments:

Post a Comment

Popular Posts

Fun Page

Powered by Blogger.