从文件中读取所需数据但保存整个文件数据

时间:2014-08-25 18:40:34

标签: java swing jtable

我使用swing制作了一个GUI,我将数据从文本文件读取到jtable, 文本文件有6列5行,3行的值为0,0.0,0,0,0,0。我想显示 JTable中的值,直到它遇到0.但保存全文文件,同时保存,这意味着5行的值。这是我的代码:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class Bb extends JFrame
{
 private JTable table;
 private DefaultTableModel model;

 @SuppressWarnings("unchecked")
 public Bb()
 {
      String aLine ;
      Vector columnNames = new Vector();
      Vector data = new Vector();

      try
      {
           FileInputStream fin = new FileInputStream("Bbb.txt");
           BufferedReader br = new BufferedReader(new InputStreamReader(fin));



           StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");

           while( st1.hasMoreTokens())
           {
                columnNames.addElement(st1.nextToken());
           }



           while ((aLine = br.readLine()) != null )
           {
                StringTokenizer st2 = new StringTokenizer(aLine, " ");
                Vector row = new Vector();

                while(st2.hasMoreTokens())
                {
                     row.addElement(st2.nextToken());
                }
                  data.addElement( row );
           }
           br.close();
      }
      catch (Exception e)
      {
           e.printStackTrace();
      }


      model = new DefaultTableModel(data, columnNames);
      table = new JTable(model);

      JScrollPane scrollPane = new JScrollPane( table );
      getContentPane().add( scrollPane );

      JPanel buttonPanel = new JPanel();
      getContentPane().add( buttonPanel, BorderLayout.SOUTH );


      JButton button2 = new JButton( "SAVE TABLE" );
      buttonPanel.add( button2 );
      button2.addActionListener( new ActionListener()
      {
           public void actionPerformed(ActionEvent e)
           {


                   if  ( table.isEditing() )
                {
                     int row = table.getEditingRow();
                     int col = table.getEditingColumn();
                     table.getCellEditor(row, col).stopCellEditing();
                }

                int rows = table.getRowCount();
                int columns = table.getColumnCount();


                try { 

StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
  {
        for  (int j = 0; j < table.getColumnCount(); j++)
     {

       Object Value = table.getValueAt(i, j);
       Con.append(" ");
           Con.append(Value);
         }
   Con.append("\r\n");
   }

FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
    fileWriter.flush();
fileWriter.close();  
        }  
        catch (Exception ex) {  
            ex.printStackTrace();  
        }  
           }
      });



 }

 public static void main(String[] args)
 {
      Bb frame = new Bb();
      frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
      frame.pack();
      frame.setVisible(true);
  }

}

和文本文件:

1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9

1 个答案:

答案 0 :(得分:0)

我能够理解你想要的东西

首先,您只想在JTable中显示您的数据,直至遇到0

<强>码

 while ((aLine = br.readLine()) != null) {
            String[] sp = aLine.split(" ");
            if (sp[0].equals("0")) {
                break;
            }
            StringTokenizer st2 = new StringTokenizer(aLine, " ");
            Vector row = new Vector();

            while (st2.hasMoreTokens()) {

                String s = st2.nextToken();
                row.addElement(s);
            }

            data.addElement(row);
        }

说明:当你读取每一行时,将其拆分,所以如果每个分割行的第一个元素为零,你就会退出循环,并且不会在循环中显示任何其他值。

要将所有数据从第一个文件保存到第二个文件,您应该将它们从第一个文件复制到第二个文件,因为JTable没有足够的信息来帮助您解决此问题。

注意:我不明白你为什么要这样做,但你可以通过以下方式实现这一目标

<强>代码:

button2.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (table.isEditing()) {
                int row = table.getEditingRow();
                int col = table.getEditingColumn();

                table.getCellEditor(row, col).stopCellEditing();
            }

            int rows = table.getRowCount();
            int columns = table.getColumnCount();

            try {
                String st = "";
                FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
                        + "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
                Scanner input = new Scanner(fin).useDelimiter("\\A");
                while (input.hasNext()) {
                    st = input.next();
                    System.out.println("st is " + st);
                }

                FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
                        + "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
                fileWriter.write(st);
                fileWriter.flush();
                fileWriter.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });

解释:您使用Scanner技巧读取整个文件并将其写入第二个文件。 资料来源:https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html

根据OP请求的内容

代码:

 public Bb() {
        String aLine;
        Vector columnNames = new Vector();
        Vector data = new Vector();
        boolean found = false;
        StringBuilder temp = new StringBuilder();
        /*Using try catch block with resources Java 7 
          Read about it
        */
        try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
                + "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {

            StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
            //the first line of the txt file fill colum names
            while (st1.hasMoreTokens()) {
                String s = st1.nextToken();
                columnNames.addElement(s);
            }

            while ((aLine = br.readLine()) != null) {
                String[] sp = aLine.split(" ");
                if (sp[0].equals("0") && !found) {
                    found = true;
                } else if (found) {
                    temp.append(aLine).append("\r\n");
                } else if (!sp[0].equals("0") && !found) {
                    StringTokenizer st2 = new StringTokenizer(aLine, " ");
                    Vector row = new Vector();
                    while (st2.hasMoreTokens()) {
                        String s = st2.nextToken();
                        row.addElement(s);
                    }
                    data.addElement(row);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        model = new DefaultTableModel(data, columnNames);
        table = new JTable(model);

        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);

        JPanel buttonPanel = new JPanel();
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        JButton button2 = new JButton("SAVE TABLE");
        buttonPanel.add(button2);
        button2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (table.isEditing()) {
                    int row = table.getEditingRow();
                    int col = table.getEditingColumn();

                    table.getCellEditor(row, col).stopCellEditing();
                }

                int rows = table.getRowCount();
                int columns = table.getColumnCount();

                try {
                    StringBuilder con = new StringBuilder();
                    for (int i = 0; i < table.getRowCount(); i++) {
                        for (int j = 0; j < table.getColumnCount(); j++) {
                            Object Value = table.getValueAt(i, j);
                            con.append(" ");
                            con.append(Value);
                        }
                        con.append("\r\n");
                    }

                    try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
                            + "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
                        fileWriter.write(con.append(temp).toString());
                        fileWriter.flush();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });

    }

如果您的行包含零,我的代码就可以正常工作。如果你想更好地掩盖所有条件,我相信你可以遵循我的计划。

取消所有零的样本

1 1 1
0 0 0
0 0 0
1 1 1

代码:

        String s = "xxxooooooxxx";
        String[] sp = s.split("");
        boolean xFlag = false;

        for (int i = 0; i < sp.length; i++) {
            if (sp[i].equals("x") && !xFlag) {
                System.out.print("x");
            } else if (sp[i].equals("o")) {
                xFlag = true;
            } else if (sp[i].equals("x") && xFlag) {
                System.out.print("X");
            }
        }

输出:

xxxXXX