Read one line of a csv file in Java

后端 未结 6 1999
Happy的楠姐
Happy的楠姐 2021-01-21 16:59

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

相关标签:
6条回答
  • 2021-01-21 17:25

    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.

    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.

    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.

    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;            
    }
    
    0 讨论(0)
  • 2021-01-21 17:34

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

    0 讨论(0)
  • 2021-01-21 17:34

    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();
    
    0 讨论(0)
  • 2021-01-21 17:39

    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 BufferedReader you 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).

    0 讨论(0)
  • 2021-01-21 17:40

    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;
    
    0 讨论(0)
  • 2021-01-21 17:44
    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
            }
    
    0 讨论(0)
提交回复
热议问题