我想从txt文件读取并写入现有的JTable [英] I want to read from a txt file and write to an existing JTable

查看:78
本文介绍了我想从txt文件读取并写入现有的JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个内部带有JTable的JFrame,并且能够在单元格上写信息.我可以单击Save JMenuItem Save,然后将信息写入txt文件中. 但是,当我尝试读取文件并将其带回到表中时,我遇到了三个问题.

I have created a JFrame with a JTable inside and I am able to write info on the cells. I can click the Save JMenuItem Save and the info is written into a txt file. However, when I try to read the file and bring it back to the Table I face three problems.

  1. JTable由30行组成.当代码读取txt文件时,在第30个文件下方添加行.有没有一种方法可以从第一行而不是第31行开始填充输入? -已解决
  2. 数据未正确写入.所有这些都写在第一栏中-已解决
  3. 如何摆脱空"字符串? -已解决

我的txt文件格式如下:

My txt file format is like this:

Number;Type;IP;Protocol;Line;
49897223040;WE4;192.168.12.98;TCP;Single;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;
null;null;null;null;null;

我的代码如下:

public class PhoneOrganiser extends JFrame {
public static void main(String[] args){


            //creation of the Window
            JFrame frame = new JFrame ("Phone Organiser");
            frame.setSize(200, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            //declaring the type of Table, Number of columns and rows
            String col[] ={"Number", "Type", "IP", "Protocol", "Line"};
            DefaultTableModel tableModel = new DefaultTableModel (col,30);

            //create the table
            JTable table = new JTable(tableModel);

            //add the Table to the scrollpane 
            JScrollPane scrollpane = new JScrollPane(table);
            frame.add(scrollpane);

            //creating the Menu bar
            JMenuBar menubar = new JMenuBar();
            frame.setJMenuBar(menubar);

            //adding menus
            JMenu file = new JMenu ("File");
            menubar.add(file);


            JMenu help = new JMenu ("Help");
            menubar.add(help);


            //adding items inside the menus
            JMenuItem open = new JMenuItem ("Open");
            file.add(open);

            JMenuItem save = new JMenuItem ("Save");
            file.add(save);



            JMenuItem exit = new JMenuItem ("Exit");
            file.add(exit);
            exit.addActionListener(new Exit());

            JMenuItem readMe = new JMenuItem ("Read me file");
            help.add(readMe);
            readMe.addActionListener(new ReadMe());
            JMenuItem about = new JMenuItem ("About");
            help.add(about);
            about.addActionListener(new About());





    //When the program starts for the first time, it creates a new txt file
    Path path = Paths.get("/Users/PhoneData.txt");
    try{
        Files.createFile(path);
        System.out.println("file created");
    }catch (IOException e1){
        System.out.println("file already exists");
    }


    //saving data from TABLE -> TO TXT - It can be done with FileChooser in V2

    class SaveData extends JFrame implements ActionListener {

        public void actionPerformed (ActionEvent e){

            try{

                File file = new File ("C:\\Users\\PhoneData.txt"); //declaring the path of the file
                FileWriter fw = new FileWriter (file.getAbsoluteFile()); 
                BufferedWriter bw = new BufferedWriter (fw);

                    //rows
                    for (int i =0; i < table.getRowCount(); i++){

                        //columns
                        for (int j=0; j < table.getColumnCount(); j++){
                            bw.write((String)table.getModel().getValueAt(i, j)+ ";"); //write the contents to the file

                        }
                        bw.write("/");
                        bw.newLine();
                    }
                    bw.close();
                    fw.close();

            }catch (IOException e2){

            }//end catch

        }//end action method


    }save.addActionListener(new SaveData()); //end SaveData class


    //reading data from TXT -> TO TABLE

    class OpenData extends JFrame implements ActionListener{

        public void actionPerformed (ActionEvent e){

            String line = null;

            try{

                File file = new File ("C:\\Users\\PhoneData.txt");
                FileReader fr = new FileReader (file.getAbsoluteFile());
                BufferedReader br = new BufferedReader (fr);

                while((line = br.readLine()) != "null;") 
                {

                    String [] splitData = line.split("/");
                    Values values = new Values();
                    values.setNumber(splitData[0]);
                    //values.setType(splitData[1]);
                    //values.setIP(splitData[2]);
                    //values.setProtocol(splitData[3]);
                    //values.setLine(splitData[4]);
                    tableModel.addRow(line.split("")); 
                }
                br.close();

            }catch (IOException e3){


            }//end catch

        }//end action method

    }open.addActionListener(new OpenData());//end OpenData class






}//end main
}//end class


public  class Values{
        private String Number;
        private String Type;
        private String IP;
        private String Protocol;
        private String Line;

        public String getNumber(){
            return Number;
        }
        public void setNumber(String Number){
            this.Number = Number;
        }


        public String getType(){
            return Type;
        }
        public void setType(String Type){
            this.Type = Type;
        }


        public String getIP(){
            return IP;
        }
        public void setIP(String IP){
            this.IP = IP;
        }


        public String getProtocol(){
            return Protocol;
        }
        public void setProtocol(String Protocol){
            this.Protocol = Protocol;
        }


        public String getLine(){
            return Line;
        }
        public void setLine(String Line){
            this.Line = Line;
        }
    }//end class Values

推荐答案

Ad.3 代码非常清楚:

Ad.3 Code is pretty much clear:

 for (int j=0; j < table.getColumnCount(); j++){
      String value = (String)table.getModel().getValueAt(i, j);
      if((value == null || "null".equals(value)){
          value = "";
      }
      bw.write(value+";"); //write the contents to the file
 }

广告2 需要在您的代码中进行简单的修改:

Ad.2 Need simple modification in your code:

StringBuilder builder = new StringBuilder();
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
String[] lineArray= builder.toString().split("/");
for(String line: lineArray){
    String[] dataArray = line.split(";");
    tableModel.addRow(dataArray);
}

广告1 希望这是您想要实现的目标.完整代码如下:

Ad.1 Hope this is something that you want to achive. Full code below:

public class PhoneOrganiser extends JFrame {
    public static void main(String[] args){


    //creation of the Window
    JFrame frame = new JFrame ("Phone Organiser");
    frame.setSize(200, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    //declaring the type of Table, Number of columns and rows
    final String col[] ={"Number", "Type", "IP", "Protocol", "Line"};
    final DefaultTableModel tableModel = new DefaultTableModel (col,30);

    //create the table
    final JTable table = new JTable(tableModel);

    //add the Table to the scrollpane
    JScrollPane scrollpane = new JScrollPane(table);
    frame.add(scrollpane);

    //creating the Menu bar
    JMenuBar menubar = new JMenuBar();
    frame.setJMenuBar(menubar);

    //adding menus
    JMenu file = new JMenu ("File");
    menubar.add(file);

    JMenu help = new JMenu ("Help");
    menubar.add(help);

    //adding items inside the menus
    JMenuItem open = new JMenuItem ("Open");
    file.add(open);

    JMenuItem save = new JMenuItem ("Save");
    file.add(save);


    JMenuItem exit = new JMenuItem ("Exit");
    file.add(exit);


    //When the program starts for the first time, it creates a new txt file
    Path path = Paths.get("/Users/PhoneData.txt");
    try{
        Files.createFile(path);
        System.out.println("file created");
    }catch (IOException e1){
        System.out.println("file already exists");
    }

    //saving data from TABLE -> TO TXT - It can be done with FileChooser in V2

    class SaveData extends JFrame implements ActionListener {

        public void actionPerformed (ActionEvent e){

            try{

                File file = new File ("C:\\Inne\\PhoneData.txt"); //declaring the path of the file
                FileWriter fw = new FileWriter (file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter (fw);

                //rows
                for (int i =0; i < table.getRowCount(); i++){

                    for (int j=0; j < table.getColumnCount(); j++){
                        String value = (String)table.getModel().getValueAt(i, j);
                        if((value == null || "null".equals(value))) {
                            value = "";
                        }
                        bw.write(value+";"); //write the contents to the file
                    }
                    bw.write("/");
                    bw.newLine();
                }
                bw.close();
                fw.close();

            }catch (IOException e2){

            }//end catch

        }//end action method


    }
    save.addActionListener(new SaveData()); //end SaveData class

    //reading data from TXT -> TO TABLE

    class OpenData extends JFrame implements ActionListener{

        public void actionPerformed (ActionEvent e){

            String line = null;
            try{

                File file = new File ("C:\\Inne\\PhoneData.txt");
                FileReader fr = new FileReader (file.getAbsoluteFile());
                BufferedReader br = new BufferedReader (fr);

                StringBuilder builder = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    builder.append(line);
                }
                String[] lineArray= builder.toString().split("/");
                table.setModel(new DefaultTableModel(col,0));
                for(String currentLine: lineArray){
                    String[] dataArray = currentLine.split(";");
                    ((DefaultTableModel)table.getModel()).addRow(dataArray);
                }
                br.close();

            }catch (IOException e3){


            }//end catch

        }//end action method

    }open.addActionListener(new OpenData());//end OpenData class

}
}

这篇关于我想从txt文件读取并写入现有的JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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