我想从txt文件中读取并写入现有的JTable

时间:2015-07-09 13:14:08

标签: java swing jtable

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

  1. JTable由30行组成。当代码读取txt文件时,在第30个下面添加行。有没有办法从第一行而不是第31行开始填充输入? - 已解决
  2. 数据写入不正确。所有这些都写在第一栏 - 求助
  3. 如何摆脱" null"串? --SOLVED
  4. 我的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
    

1 个答案:

答案 0 :(得分:2)

Ad.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
 }

Ad.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);
}

Ad.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

}
}