0

How to read files and insert data count into JTable?

I have n number of text files. What I need to do is to read data from each file and insert the data count of each corresponding file into Java table such that:

File Name          Total records exist
-----------------------------------------
x1.txt                    457
x2.txt                    876
.                         .
.                         .
.                         .
xn.txt                    345
-----------------------------------------
Total                     1678
-----------------------------------------

Can you please help me out with some ideas to achieve the same?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • *"Can you please help me out with some ideas to achieve the same?"* 1) See [Starting Writing a Program](http://home.earthlink.net/~patricia_shanahan/beginner.html) for great tips. 2) [What have you tried?](http://www.whathaveyoutried.com/) I mean *besides* asking us. – Andrew Thompson May 10 '13 at 10:33
  • @AndrewThompson: I am trying with Hashmap, taking buffer-reader and increasing the count as every line is read, then trying to put the final count value in hashmap. – Andrews R. Dean May 10 '13 at 10:40
  • *"I am trying.."* Explain better with an [SSCCE](http://sscce.org/). – Andrew Thompson May 10 '13 at 10:41
  • Where is the code you havea tried with? – Stanley Mungai May 10 '13 at 10:44

1 Answers1

1

Arrange for your read method to accept a File and return a Map<String, Integer>.

private Map<String, Integer> readData(File file) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    // fill in the map from the file
    return map;
}

Once you have the Map, you can build a TableModel around it, as shown in this EnvTableTest.

private static class FileDataModel extends AbstractTableModel {

    private Map<String, Integer> data = readData(file);
    private String[] keys;

    public FileDataModel() {
        keys = data.keySet().toArray(new String[data.size()]);
    }
    ...
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045