用 Java 读取 csv 文件的一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18033750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:55:54  来源:igfitidea点击:

Read one line of a csv file in Java

javacsv

提问by user2603112

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

我有一个当前有 20 行数据的 csv 文件。数据包含员工信息,格式如下:

first name, last name, Employee ID

名字、姓氏、员工 ID

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

所以有一行是这样的: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.

我知道如何在 Java 中写入文件并将所有 20 行都打印到控制台,但是我不确定如何让 Java 将特定行打印到控制台。

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.

我还想获取最后一个条目中的最后一个员工 ID 号,并让 java 添加 1 一个我添加新员工。我认为这需要用计数器来完成,只是不确定如何。

回答by micha

You can do something like this:

你可以这样做:

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));

With BufferedReaderyou 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).

随着BufferedReader您可以直接读取线。此示例逐行读取文件并将行存储在数组列表中。您可以使用lines.get(lineNumber).

回答by Caffe Latte

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
        }

回答by R Dub

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;

回答by R Dub

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..

或者,如果您想更多地控制读取的 CSV 文件,那么您可以考虑 CsvBeanReader,它可以让您更多地访问文件内容。

回答by George T 97

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.

这是我用于读取 csv 文件的算法。最有效的方法是先将csv文件中的所有数据读入二维数组。它只是使操作数据更加灵活。

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.

通过这种方式,您可以通过在数组的索引中指定文件的哪一行并使用 for 来指定将文件的哪一行打印到控制台。即: System.out.println(employee_Data[1][y]); 对于记录 1。y 是字段的索引变量。当然,您需要使用 For 循环来打印每一行的每个元素。

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.

顺便说一句,如果您想在更大的程序中使用员工数据,例如,它可以将数据存储在数据库中或写入另一个文件,我建议将整个代码块封装到名为 Read_CSV_File( ),这将返回一个二维字符串数组。

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;            
}

回答by Jobin Mathew

For reading large file,

对于读取大文件,

log.debug("****************Start Reading CSV File*******");
    copyFile(inputCSVFile);
    StringBuilder stringBuilder = new StringBuilder();
    String line= "";
    BufferedReader brOldFile = null;
    try {
        String inputfile = inputCSVFile;
        log.info("inputfile:" + inputfile);
        brOldFile = new BufferedReader(new FileReader(inputfile));
        while ((line = brOldFile.readLine()) != null) {
            //line  =   replaceSpecialChar(line);
            /*do your stuff here*/
            stringBuilder.append(line);
            stringBuilder.append("\n");
        }

        log.debug("****************End reading CSV File**************");
    } catch (Exception e) {
        log.error(" exception in readStaffInfoCSVFile ", e);
    }finally {
        if(null != brOldFile) {
            try {
                brOldFile.close();
            } catch (IOException e) {
            }
        }
    }
    return stringBuilder.toString();