Вот алгоритм, который я использую для чтения csv-файлов. Самый эффективный способ - сначала прочитать все данные в файле csv в 2D-массив. Это просто делает его намного более гибким для манипулирования данными.
Таким образом, вы можете указать, какую строку файла распечатать на консоли, указав ее в индексе массива и используя for. I.e: System.out.println (employee_Data [1] [y]); для записи 1. y - индексная переменная для полей. Конечно, вам нужно будет использовать цикл For Loop, чтобы печатать каждый элемент для каждой строки.
Кстати, если вы хотите использовать данные сотрудника в более крупной программе, в которой он может, например, хранить данные в базе данных или записывать в другой файл, я бы рекомендовал инкапсулировать весь этот код блок в функцию с именем Read_CSV_File (), которая вернет массив 2D String.
Мой код
// 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;
}