【问题标题】:Read one line of a csv file in Java用Java读取一行csv文件
【发布时间】:2013-08-04 17:15:33
【问题描述】:

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

名字、姓氏、员工 ID

所以一行是这样的:Emma, Nolan, 2

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

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

【问题讨论】:

标签: java csv


【解决方案1】:

你可以这样做:

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) 访问之后的行。

【讨论】:

  • 所以如果我想让它成为自己的类,然后从另一个类中调用它,我还会使用lines.get(lineNumber) 来访问它吗?
  • 取决于你如何设计你的课程。您还可以向您的类添加一个 getFirstLine() 方法,该方法在内部使用 lines.get(0) 或类似的东西。
  • 记得关闭它。
【解决方案2】:
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
        }

【讨论】:

  • 我会在字符串之后放一个数字,所以 String [2] 和 line.trim (20) 之后?
  • 这是不可取的,因为您的 CSV 字段可能包含在引号中。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

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

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

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

      我的代码

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

      【讨论】:

        【解决方案6】:

        用于读取大文件,

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-17
          • 1970-01-01
          • 2014-01-26
          • 2022-11-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多