使用OpenCSV获取列数

时间:2014-08-09 11:58:46

标签: java opencsv

我有一个txt文件,我想计算列数。 (我使用openCSV)

public class demoTable {
    public demoTable(){
         read();
        JOptionPane.showMessageDialog(null, "number of columns inside file: " + getNumberOfColumnsFromFile(), null, JOptionPane.INFORMATION_MESSAGE);
    close();
    }

    private void read(){
    try {
        this.fileInputStream = new FileInputStream("D:\\Book3.txt");
        UTF8_CHARSET = StandardCharsets.UTF_8.newDecoder();
        UTF8_CHARSET.onMalformedInput(CodingErrorAction.REPLACE);
        this.fileReader = new InputStreamReader(this.fileInputStream, UTF8_CHARSET);
        this.reader = new CSVReader(this.fileReader, '\t');
    } 
    catch (FileNotFoundException ex) {
        Logger.getLogger(VJTable.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

    private int getNumberOfColumnsFromFile(){
    //Estimating number of rows from file (Googled that).
    this.numberOfColumns = 0;
    try {
        while( (this.nextLine = this.reader.readNext()) != null){
            this.numberOfColumns++;
        }
    } 
    catch (IOException ex) {
        Logger.getLogger(VJTable.class.getName()).log(Level.SEVERE, null, ex);
    }
    return this.numberOfColumns;
   }

   private void close(){
    try {
        this.fileInputStream.close();
        this.fileReader.close();
        this.reader.close();
    }
    catch (IOException ex) {
        Logger.getLogger(VJTable.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
}

不幸的是,getNumberOfColumnsFromFile()方法返回行数而不是列数。你能告诉我在这里做得不好吗?提前谢谢。

1 个答案:

答案 0 :(得分:3)

CSVRearder.readNext()方法返回String[],其中每列/值都是一个元素:

  

从缓冲区读取下一行并转换为字符串数组[..],每个逗号分隔元素作为单独的条目。

因此,

String[] header = this.reader.readNext(); // assuming first read
if (header != null) {                     // and there is a (header) line
   int columnCount = header.length;       // get the column count
}