java - 使用 OpenCSV 获取列数

标签 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() 方法返回行数而不是列数。你能告诉我我在这里做的不好吗?提前谢谢你。

最佳答案

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

Reads the next line from the buffer and converts to a string array [..] with each comma-separated element as a separate entry.

因此,

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
}

关于java - 使用 OpenCSV 获取列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25218343/

相关文章:

java - 使用 CSV 解析器解析 CSV 文件时忽略字段中的双引号

java - MySql 中包含逗号的 CSV 数据插入失败

java - hibernate 查找表 : As an Object Relation or as a code/key

java - 使用方法将 ArrayList 复制到文本文件

java - VisualVM - 奇怪的自拍时间

java - Netbeans 图形用户界面生成器

java - 使用java将数据库(DB2)元组作为XML元素插入XML文件中?

java - 动态设置 OpenCSVReader 映射的类类型和类

java - 在java中将流文件写入zip流

java - 将解析的 CSV 文件插入 SQL Server