读取没有第三方库的CSV文件

时间:2012-11-14 17:37:39

标签: java csv arraylist stringtokenizer

我正在尝试将csv文件读入ArrayList或String [] []数组。在这里我试图将它读入一个列表,然后使用一个标记器将列表组成一个数组。 csv文件有7列(A - G)和961行(1-961)。我的for循环为2D数组保持返回空指针,但我认为它应该工作..

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

2 个答案:

答案 0 :(得分:3)

在使用之前将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

答案 1 :(得分:0)

您可以使用此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;
    }