1

我需要从 csv 文件中读取数据,并且对我来说更方便的是 2D 数组(在我看来,这是处理这个“计划”数据的最简单方法)。每个文件行包含以下格式的信息:

Instructor, Course, Group, Student, Result

如下示例:

Paul Schwartz,Introduction to Computer Architecture,I1,Ben Dunkin,88
Muhamed Olji,Object Oriented Programming,I4,Mike Brown,73

但是我的代码需要一些简化。但我不知道如何让它变得更容易并问

代码:

private String[][] fileContent(String pathToCSVFile) {
    final int ROWS = 100;
    final int COLUMNS = 5;
    String fileData[][] = new String[ROWS][COLUMNS];
    Scanner scanner = new Scanner(pathToCSVFile);
    boolean done = false;
    int i, j;

    while (!done) {
        for (i = 0; i >= 0; i++) {
           for (j = 0; j >= 0; j++) {
               String str[] = scanner.nextLine().split(","); 
               for (int element = 0; element < str.length; element++) {
                   fileData[i][element] = str[element];
                   if (i >= ROWS) {
                       Arrays.copyOf(fileData, fileData.length * 2);
                   }
               }                   
           }
        }

        if (!scanner.hasNextLine()) done = true;
    }

    return  fileData;
}
  • 如何重构这段代码以获得更好的简洁性?
  • 对于部分填充的数组(比)是否存在更好的方法Arrays.copyOf(fileData, fileData.length * 2)
4

2 回答 2

3

Using openCSV, you can get a list containing all the lines and convert it to an array (or just keep the list):

try (CSVReader reader = new CSVReader(new BufferedReader(
          new FileReader(pathToCSVFile)));) {

    List<String[]> lines = reader.readAll();
    return lines.toArray(new String[lines.size()][]);
}

(using Java 7 try-with-resources syntax)

于 2013-08-05T11:11:50.127 回答
1

First of all, be careful with those for loops. They are "almost" undefined loops, because they start with i,j=0, and loop while >=0 (always, until they overflow into a negative number). And why do you need them anyway? I think with you while and the for(element) you are done, right? Something like that (I didn't tried, is just to explain the concept)

private String[][] fileContent(String pathToCSVFile) {
    final int ROWS = 100;
    final int COLUMNS = 5;
    String fileData[][] = new String[ROWS][COLUMNS];
    Scanner scanner = new Scanner(pathToCSVFile);
    boolean done = false;
    int i=0;

    while (!done) {
        String str[] = scanner.nextLine().split(","); 
        for (int element = 0; element < str.length; element++) {
            fileData[i][element] = str[element];
            if (i >= ROWS) {
                Arrays.copyOf(fileData, fileData.length * 2);
            }
        }
        if (!scanner.hasNextLine())
            done = true;
        else
            i++;
    }
    return  fileData;
}

By the way, why don't you use objects, like an ArrayList? It would make your life easier, so you don't have to worry about memory handling. You just add new objects.

Something like an ArrayList <ArrayList <String>>

于 2013-08-05T10:41:42.540 回答