首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用OpenCSV获取列数

使用OpenCSV获取列数
EN

Stack Overflow用户
提问于 2014-08-09 19:58:46
回答 1查看 9.2K关注 0票数 3

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

代码语言:javascript
运行
复制
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()方法返回的是行数而不是列数。你能告诉我我在这里做得不好的地方吗?提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-09 20:06:49

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

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

因此,

代码语言:javascript
运行
复制
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
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25218343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档