用Java读取csv文件的一行

时间:2013-08-03 14:16:12

标签: java csv

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

名字,姓氏,员工ID

所以一行会这样:Emma,Nolan,2

我知道如何在java中写入文件并将所有20行打印到控制台,但我不知道该怎么做才能让Java将一条特定的行打印到控制台。< / p>

我还想在最后一个条目中获取最后一个员工ID号,并在添加新员工时将java添加1。我认为这需要通过计数器来完成,而不知道如何。

6 个答案:

答案 0 :(得分:5)

您可以这样做:

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)

访问之后的行

答案 1 :(得分:1)

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
        }

答案 2 :(得分:0)

您可以一次一行地读取文件中的文本,然后对该行执行任何操作,打印,比较等等...

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

答案 3 :(得分:0)

或者,如果您想要更多地控制读取CSV文件,那么您可以考虑使用CsvBeanReader来提供对文件内容的更多访问权限。

答案 4 :(得分:0)

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

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

顺便说一句,如果你想在一个更大的程序中使用员工数据,例如它可以将数据存储在数据库中或写入另一个文件,我建议将整个代码块封装到一个函数中名为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;            
}

答案 5 :(得分:0)

要读取大文件,

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