Прочитать только первую строку CSV-файла из Интернета с использованием Java [duplicate]

Также, если вы используете сторонние библиотеки, убедитесь, что у вас есть правильные 32/64 битные файлы

2
задан user2603112 3 August 2013 в 15:16
поделиться

5 ответов

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
        }
1
ответ дан Caffe Latte 24 August 2018 в 15:50
поделиться

Вот алгоритм, который я использую для чтения 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;            
}
0
ответ дан George T 97 24 August 2018 в 15:50
поделиться

Вы можете сделать что-то вроде этого:

BufferedReader reader = new BufferedReader(new FileReader(<<your file>>));
List<String> lines = new ArrayList<>();
String line = null;
while ((line = reader.readLine()) != null) {
    lines.add(line);
}

System.out.println(lines.get(0));

С помощью BufferedReader вы можете читать строки напрямую. В этом примере файл читается строка за строкой и сохраняет строки в списке массивов. После этого вы можете получить доступ к строкам с помощью lines.get(lineNumber).

5
ответ дан micha 24 August 2018 в 15:50
поделиться

Вы можете читать текст из файла по одной строке за раз, а затем делать все, что хотите, с этой линией, печатать, сравнивать и т. д. ...

// 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;
0
ответ дан R Dub 24 August 2018 в 15:50
поделиться

В качестве альтернативы, если вы хотите больше контролировать чтение CSV-файлов, тогда вы можете подумать о CsvBeanReader, который даст вам больше доступа к содержимому файлов.

0
ответ дан user 24 August 2018 в 15:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: