跳过插入csv文件的第一行

时间:2012-01-03 22:37:32

标签: java csv stringtokenizer

我有一个方法从.csv文件中获取数据并将其放入数组中 (第一行进入最后一个数组槽)但是我希望.csv文件中的第一行不在数组中。我怎么做到这一点?这是我到目前为止的代码:

public static String[][] parse(String symbol) throws Exception{

    String destination = "C:/"+symbol+"_table.csv"; 

    LineNumberReader lnr = new LineNumberReader(new FileReader(new File(destination)));
    lnr.skip(Long.MAX_VALUE);

    String[][] stock_array = new String[lnr.getLineNumber()][3];

    try{
        BufferedReader br = new BufferedReader(new FileReader(destination));
        String strLine = "";
        StringTokenizer st = null;

        int line = lnr.getLineNumber()-1;

        while((strLine = br.readLine()) != null){           
            st = new StringTokenizer(strLine, ",");

            while(st.hasMoreTokens()){                  
                stock_array[line][0] = st.nextToken();
                        st.nextToken();
                stock_array[line][1] = st.nextToken();
                stock_array[line][2] = st.nextToken();
                        st.nextToken();
                        st.nextToken();
                        st.nextToken();
            }
            line--; 
        }
    }
    catch(Exception e){
        System.out.println("Error while reading csv file: " + e);
    }
    return stock_array;
}

2 个答案:

答案 0 :(得分:2)

你可以跳过第一行,只读它并什么都不做。在你的while循环之前执行此操作:

br.readLine();

为确保您的阵列尺寸合适且线条存放在正确的位置,您还应进行以下更改:

String[][] stock_array = new String[lnr.getLineNumber()-1][3];
...
int line = lnr.getLineNumber()-2;

答案 1 :(得分:1)

据我所知,您的代码效率不高。此外,您正在使用linenumberreader.skip(long.max_value),这不是一种正确/确认的方法来查找文件的行数。 StringTokenizer是一种不推荐的拆分令牌方式。我会用以下方式编写代码:

public static List<String[]> parse(String symbol) throws Exception {
        String destination = "C:/"+symbol+"_table.csv";
        List<String[]> lines = new ArrayList<String[]>();

        try{
            BufferedReader br = new BufferedReader(new FileReader(destination));
            int index = 0;

            while((line = br.readLine()) != null){
                if(index == 0) {
                   index++;
                   continue; //skip first line
                }

                lines.add(line.split(","));
            }

            if(lines != null && !lines.isEmpty()) {
                Collections.reverse(lines);
            }
        } catch(IOException ioe){
            //IOException Handling
        } catch(Exception e){
            //Exception Handling
        }

        return lines;
    }