3

I have a txt file and I want to count the number of columns. (I use 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);
    }
    }
}

Unfortunately, the getNumberOfColumnsFromFile() method returns the number of rows instead of columns. Could you please tell me what I don't do well in here? Thank you in advance.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Vassilis De
  • 363
  • 1
  • 3
  • 21

1 Answers1

4

The CSVRearder.readNext() method returns a String[], where each column/value is an element:

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

Thus,

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
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • @VassilisDe You're welcome! Remember that it does read-past a line. – user2864740 Aug 09 '14 at 14:32
  • I'm afraid I didn't understand that...could you please explain to me? – Vassilis De Aug 09 '14 at 17:42
  • Maybe a bit late, but i think what @user2864740 meant is when you read the next line from the buffer, your pointer moves past this line. Say you use this snippet to get the number of columns of your csv, next time you will call readNext(), you will get the second line. If your first line is not the header line with the fields names and contains "actual" data, you should consider this behaviour. – KevinD Jun 09 '16 at 11:40