java - 我想从 txt 文件读取数据并写入现有的 JTable

标签 java swing jtable

我创建了一个 JFrame,里面有一个 JTable,我可以在单元格上写入信息。我可以单击 Save JMenuItem Save 并将信息写入 txt 文件。 但是,当我尝试读取该文件并将其带回到表中时,我面临三个问题。

  1. JTable 由 30 行组成。当代码读取 txt 文件时,在第 30 行下方添加行。有没有办法从第一行而不是第 31 行开始填充输入? -- 已解决
  2. 数据写入不正确。所有这些都写在第一栏——已解决
  3. 如何去掉“null”字符串? --已解决

我的txt文件格式是这样的:

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

最佳答案

广告.3 代码非常清晰:

 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 需要对代码进行简单修改:

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 希望这是您想要实现的目标。完整代码如下:

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

}
}

关于java - 我想从 txt 文件读取数据并写入现有的 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318587/

相关文章:

java - 使用 Swing 的多线程

java - 如何解决Java中预期的分号错误?

java - 如何找到所有空按钮并随机选择一个?

java - 将 Zxing 条码扫描仪集成到我的 Android 应用程序中

java - 仅在单击鼠标 Swing 时打开 popupMenu

java - 使用 Map 的内容填充 JTable

java - 如何使用 JTable 鼠标单击事件将图像从 JTable 显示到 JLabel 或从数据库显示到 JLabel?

java - 如何在 JTable 中添加行?

java - InputStream 无法处理 2016 字节

java - 将目录存储为文件对象还是字符串?