2

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.

4

6 回答 6

7

你可以这样做:

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)

于 2013-08-03T14:26:12.383 回答
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
        }
于 2013-08-03T14:26:50.930 回答
1

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

// 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;
于 2013-08-03T14:34:08.263 回答
0

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

于 2013-11-11T13:36:44.503 回答
0

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

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

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

我的代码

// 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;            
}
于 2016-03-08T22:53:54.817 回答
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();
于 2019-05-10T10:27:56.607 回答