读取文本文件并将其显示在Jtable中? [英] Read text file and display it in Jtable?

查看:153
本文介绍了读取文本文件并将其显示在Jtable中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要逐行读取文本文件的内容并将其显示在Jtable上,该表应可由用户根据需要进行编辑,不胜感激.我是Java新手.谢谢.

i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.

我的文本文件:文件名(people.txt)

My Text File: File Name(people.txt)

COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY  COLUMN_DEFAULT  EXTRA   
Names   VARCHAR(500)    NO  
Address VARCHAR(500)    NO

到目前为止我的代码:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
    static public void main(String[] arg){
        JScrollPane scroll;
        JTable table;
        DefaultTableModel model;
        String fname="people";
        try
        {
            FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");


            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine,str = null;
            //Read File Line By Line
            String text = "";
            Vector myVector = new Vector();
            while ((strLine = br.readLine()) != null) //loop through each line
            {
                myVector.add(strLine );
                // Print the content on the console
                text +=(strLine+"\n");  // Store the text file in the string
            }
            in.close();//Close the input stream
            int i=0;
            String fline=myVector.elementAt(0).toString();
            String[] sp=fline.split("\\s+");
            for(String spt:sp){
                System.out.println(spt);
                //model = new DefaultTableModel(spt, );   // I dont know how to put the strings
                into Jtable here
                table = new JTable(){
                    public boolean isCellEditable(int row, int column){
                        return false;
                    }
                };
                int a=0;// for text box name
                for(i=1;i<myVector.size();i++){
                    str=myVector.elementAt(i).toString();
                    String[] res =str.split("\\s+");
                    int k=0;
                    for(String st:res)
                    System.out.println(st);
                k++;a++; }
        } }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

谢谢.

推荐答案

文件内容:(每个属性用分号分隔,每行都是一条记录.)

File Content: (Each attribute is separated by a semicolon and each line is a record.)

Hello1; 123

Hello1;123

World1; 234

World1;234

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class FileToJTable {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            public void run() {
                new FileToJTable().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {

        try {
            JFrame frame = new JFrame();
            frame.setLayout(new BorderLayout());
            JTable table = new JTable();

            String readLine = null;

            StudentTableModel tableModel = new StudentTableModel();
            File file = new File(""/*Give your File Path here*/);

            FileReader reader = new FileReader(file);
            BufferedReader bufReader = new BufferedReader(reader);

            List<Student> studentList = new ArrayList<Student>();
            while((readLine = bufReader.readLine()) != null) {
                String[] splitData = readLine.split(";");

                Student student = new Student();
                student.setName(splitData[0]);
                student.setNumber(splitData[1]);

                studentList.add(student);
            }

            tableModel.setList(studentList);
            table.setModel(tableModel);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new JScrollPane(table));
            frame.setTitle("File to JTable");
            frame.pack();
            frame.setVisible(true);

        } catch(IOException ex) {}
    }

    class Student {

        private String name;
        private String number;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getNumber() {
            return number;
        }
        public void setNumber(String number) {
            this.number = number;
        }
    }

    class StudentTableModel extends AbstractTableModel {

        private List<Student> list = new ArrayList<Student>();
        private String[] columnNames = {"Name", "Number"};

        public void setList(List<Student> list) {
            this.list = list;
            fireTableDataChanged();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        public int getRowCount() {
            return list.size();
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
            case 0:
                return list.get(rowIndex).getName();
            case 1:
                return list.get(rowIndex).getNumber();
            default:
                return null;
            }
        }
    }
}

这篇关于读取文本文件并将其显示在Jtable中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆