在没有第三方库的情况下读取 CSV 文件



>我正在尝试将csv文件读取到ArrayList或String [][]数组中。在这种情况下,我尝试将其读入列表,然后使用分词器将列表形成到数组中。csv 文件有 7 列 (A - G) 和 961 行 (1-961)。我对 2D 数组的 for 循环一直返回一个空指针,但我认为它应该可以工作。

public class FoodFacts
{
    private static BufferedReader textIn;
    private static BufferedReader foodFacts;
            static int numberOfLines = 0; 
            static String [][] foodArray;
    public static String  aFact;
    static  int NUM_COL = 7;
    static int NUM_ROW = 961;
    // Make a random number to pull a line
    static Random r = new Random();
    public static void main(String[] args)
    {
        try 
        {
            textIn = new BufferedReader(new InputStreamReader(System.in));
            foodFacts= new BufferedReader(new FileReader("foodfacts.csv"));
            Scanner factFile = new Scanner(foodFacts);
            List<String> facts = new ArrayList<String>();
            String fact;
            System.out.println("Please type in the food you wish to know about.");
            String request = textIn.readLine();
            while ( factFile.hasNextLine()){
                fact = factFile.nextLine();
                StringTokenizer st2 = new StringTokenizer(fact, ",");
                //facts.add(fact);
                numberOfLines++;
                while (st2.hasMoreElements()){
                    for ( int j = 0; j < NUM_COL ; j++) {
                        for (int i = 0; i < NUM_ROW ; i++){
                            foodArray [j][i]= st2.nextToken();  //NULL POINTER HERE
                            System.out.println(foodArray[j][i]);
                        }
                    }
                }
            }
        }
        catch (IOException e)
        {
            System.out.println ("Error, problem reading text file!");
            e.printStackTrace();
        }
     }
 }

在使用foodArray之前将其初始化为foodArray = new String[NUM_ROW][NUM_COL];

此外,不需要内部for循环,因为您一次读取一行。

使用numberOfLines作为行:

        while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
                 fact = input.nextLine();
                 StringTokenizer st2 = new StringTokenizer(fact, ",")    ;
                 //facts.add(fact);
                while (st2.hasMoreElements()){
                  for ( int j = 0; j < NUM_COL ; j++) {
                    foodArray [numberOfLines][j]= st2.nextToken(); 
                    System.out.println(foodArray[numberOfLines][i]);
                 }
                }  
                 numberOfLines++;
            }

或者,我认为您可以使用split一次获取所有列,例如

        while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
           fact = input.nextLine();
           foodArray [numberOfLines++] = fact.split(",");
        }

一个问题:将所有变量声明为静态类变量有什么特定目的吗?它们中的大多数适合作为方法内的局部变量,例如 numberOfLines

您可以使用

String [][] foodArray = csvreadString(filename);方法。它实际上读取文件两次,但我不知道如何在不读取数据的情况下获取 csv 维度(您需要维度才能初始化数组),与我尝试过的其他方法相比,这非常快。

   static public class PairInt {
        int rows = 0;
        int columns = 0;
    }
   static PairInt getCsvSize(String filename) throws Throwable {
        PairInt csvSize = new PairInt();
        BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
        String line;
        while ((line = reader.readLine()) != null) {
            if (csvSize.columns == 0) {
                csvSize.columns = line.split(",").length;
            }
            csvSize.rows++;
        }
        reader.close();
        return csvSize;
    }
    static String[][] csvreadString(String filename) throws Throwable {
        PairInt csvSize = getCsvSize(filename);
        String[][] data = new String[csvSize.rows][csvSize.columns];
        BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
        for (int i = 0; i < csvSize.rows; i++) {
            data[i] = reader.readLine().split(",");
        }
        return data;
    }

相关内容

  • 没有找到相关文章

最新更新