Share on Google+Share on Google+

Java insert file data to JTable

In this section, you will learn how to insert text file data into JTable.

Java insert file data to JTable

In this section, you will learn how to insert text file data into JTable.

Swing has provide useful and sophisticated set of GUI components. It provides a native look and feel that emulates the look and feel of several platforms. In the given example, we have used these components.

You can see in the given example, we have extended our class with AbstractTableModel to inherit its methods and properties. Now we have read the file and store the data into vector. Then pass the vector value as a parameter to the  JTable class.

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");

 Through the above code, you can insert the file data into JTable.


Posted on: June 12, 2006 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.