Share on Google+Share on Google+

Extract File data into JTable

In this section, you will learn how to read the data from the text file and insert it into JTable.

Extract File data into JTable

In this section, you will learn how to read the data from the text file and insert it into JTable. For this, we have created a java class that extends the AbstractTableModel which provides default implementations for most of the methods in the TableModel interface. Using the BufferedReader class, we have read the data of the file. This data is then broken into tokens using StringTokenizer class.These token are then stored in Vector and displayed on the table.

Here is the student.txt:

Id  Name  Course  Department

1   A       MCA   ComputerScience

2   B       Btech   Mechanical

3   C       Btech   Electrical

4   D       MBA   Management

Here is the code:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;

public class InsertFileDataToJTable extends AbstractTableModel {
	Vector data;
	Vector columns;

	public InsertFileDataToJTable() {
		String line;
		data = new Vector();
		columns = new Vector();
		try {
			FileInputStream fis = new FileInputStream("student.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
			while (st1.hasMoreTokens())
			while ((line = br.readLine()) != null) {
				StringTokenizer st2 = new StringTokenizer(line, " ");
				while (st2.hasMoreTokens())
		} catch (Exception e) {

	public int getRowCount() {
		return data.size() / getColumnCount();

	public int getColumnCount() {
		return columns.size();

	public Object getValueAt(int rowIndex, int columnIndex) {
		return (String) data.elementAt((rowIndex * getColumnCount())
				+ columnIndex);

	public static void main(String s[]) {
		InsertFileDataToJTable model = new InsertFileDataToJTable();
		JTable table = new JTable();
		JScrollPane scrollpane = new JScrollPane(table);
		JPanel panel = new JPanel();
		JFrame frame = new JFrame();
		frame.add(panel, "Center");




Posted on: December 12, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null