如何逐行读取文本文件直到文件末尾?

时间:2014-05-21 17:48:18

标签: java swing file-io jtable

    import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;


public class DataDisplay extends JFrame{
    JTable table;
    public static JLabel jl1= new JLabel("Activity ID");
    public static JTextField jt1= new JTextField("Enter Activity ID");

    public static JLabel jl2= new JLabel("Activity name");
    public static JTextField jt2 = new JTextField("Enter Activity name");

    public static JLabel jl3= new JLabel("Start Date");
    public static JTextField jt3= new JTextField("Enter Start Date");

    public static JLabel jl4 = new JLabel("End Date");
    public static JTextField jt4= new JTextField("Enter End Date");

    public static JLabel jl5 = new JLabel("Alarm Before");
    public static JTextField jt5= new JTextField("enter alarm");
    public static JLabel jl= new JLabel("HOURS");


    public static JButton save = new JButton("SAVE");
    public static JButton close = new JButton("CLOSE");
    public Container c= this.getContentPane();

    private static int counter=0;
    DataDisplay(){

        this.setTitle("Assignment 3");
        this.setLayout(null);
        this.setBackground(Color.MAGENTA);
        c.add(jl1);
        c.add(jt1);
        c.add(jl2);
        c.add(jt2);
        c.add(jl3);
        c.add(jt3);
        c.add(jl4);
        c.add(jt4);
        c.add(jl5);
        c.add(jt5);
        c.add(jl);


        jl1.setBounds(10, 10, 100, 100);
        jt1.setBounds(100, 45, 100, 30);

        jl2.setBounds(10,60,100,100);
        jt2.setBounds(100,100,120,30);

        jl3.setBounds(10,110,100,100);
        jt3.setBounds(100,145,120,30);

        jl4.setBounds(10,160,100,100);
        jt4.setBounds(100,200,120,30);

        jl5.setBounds(10,210,100,100);
        jt5.setBounds(100,250,120,30);
        jl.setBounds(230,210,100,100);


        c.add(save);
        save.setBounds(10,300,100,30);
        save.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                int ce=0;
                // TODO Auto-generated method stub
                String tableHeader[] ={"Activity ID", "Activity name", "Start Date", "End Date","Alarm before (Hours)"};
                String tableData[][]= new String[ce=counter+1][10];
                table = new JTable(tableData, tableHeader);

                String line=null;

                BufferedReader b=null;


                try {
                    b = new BufferedReader(new FileReader("Activity.txt"));
                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                try {
                    int row=0,col=0;
                    while ((line=b.readLine())!=null){
                        String[] s= new String[100];



                        for(int counterc=1; counterc<=4; counterc++ ){//*ARRAY OUT OF BOUND EXCEPTION*
                         s=line.split("|",4);


                        }



                            tableData[row][0]=s[0];
                            tableData[row][1]=s[1];
                            tableData[row][2]=s[2];
                            tableData[row][3]=s[3];


                        row++;

                }} catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                finally{

                    try {
                        b.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }




                tableData[counter][0]=jt1.getText();
                tableData[counter][1]=jt2.getText();
                tableData[counter][2]=jt3.getText();
                tableData[counter][3]=jt4.getText();
                tableData[counter][4]=jt5.getText();


                JScrollPane scrollPane = new JScrollPane(table);
                c.add(scrollPane, BorderLayout.CENTER);
                scrollPane.setBounds(10, 400, 700, 600);
                counter++;
                try{
                    FileWriter out= new FileWriter("Activity.txt",true);
                    BufferedWriter br= new BufferedWriter(out);
                    PrintWriter p= new PrintWriter(br);
                    p.println(jt1.getText()+"|"+jt2.getText()+"|"+jt3.getText()+"|"+jt4.getText()+"|"+jt5.getText());
                    p.close();

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

                }
            }

        });

        c.add(close);
        close.setBounds(200,300,100,30);

        this.setBounds(100,100,1000,1000);
        this.setVisible(true);
        c.setVisible(true);

    }

    public static void main(String args[]){

        DataDisplay dd= new DataDisplay();
    }

}

这是我的代码。仅显示表中最后输入的行而不是初始行。我也使用了while(readline != null)但是它给出了空指针异常或数组超出范围的异常。那么我应该在while循环中放入什么条件?

5 个答案:

答案 0 :(得分:1)

建议在apache commons中使用IOUtils是不好的形式?

LineIterator lineIterator = null;
try {
    lineIterator = FileUtils.lineIterator( new File( "" ) );
    while(lineIterator.hasNext()) {
        final String next = lineIterator.next();
        // do stuff with the line eg: 
        // eg: final String[] strings = StringUtils.split( next, '|' ); ...
    }
} catch( final IOException e ) {
    // use a logger to show error
}
finally {
    if( lineIterator != null ) {
        lineIterator.close();
    }
}

答案 1 :(得分:0)

我已按以下方式更改了您的代码:

    save.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {
            int ce=0;
            // TODO Auto-generated method stub
            String tableHeader[] ={"Activity ID", "Activity name", "Start Date", "End Date","Alarm before (Hours)"};
            String tableData[][]= new String[ce=counter+1][5];
            table = new JTable(tableData, tableHeader);

            String line=null;

            BufferedReader b=null;


            try {
                b = new BufferedReader(new FileReader("Activity.txt"));
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                int row=0,col=0;
                line = b.readLine();
                    while (line != null) {
                        String[] s;

                        s = line.split("~");
                        for(int i = 0; i < s.length; i++) {
                            tableData[row][i]=s[i];
                        }
                    row++;
                    line = b.readLine();

            }} catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{

                try {
                    b.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }




            tableData[counter][0]=jt1.getText();
            tableData[counter][1]=jt2.getText();
            tableData[counter][2]=jt3.getText();
            tableData[counter][3]=jt4.getText();
            tableData[counter][4]=jt5.getText();


            JScrollPane scrollPane = new JScrollPane(table);
            c.add(scrollPane, BorderLayout.CENTER);
            scrollPane.setBounds(10, 400, 700, 600);
            counter++;
            try{
                FileWriter out= new FileWriter("Activity.txt",true);
                BufferedWriter br= new BufferedWriter(out);
                PrintWriter p= new PrintWriter(br);
                p.println(jt1.getText()+"~"+jt2.getText()+"~"+jt3.getText()+"~"+jt4.getText()+"~"+jt5.getText());
                p.close();

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

            }
        }

    });

我改变了分裂角色。我相信管道造成了一些问题。

答案 2 :(得分:0)

  1. 请务必在BufferedReader区块中关闭finally
  2. 当阅读器到达文件末尾时,
  3. readLine方法将返回null。因此,您应该将while条件编辑为!= null
  4. 您的for (int counterc = 1; counterc <= 4; counterc++)没有意义(或者至少,我没有看到它。)
  5. 您需要拆分行,然后将其保存在数组中。
  6. 为什么你有col
  7. s的数组100,而您只存储了4个元素?
  8. Split将创建一个数组,因此使用new String[4];创建的数组将被丢失。因此,请将line.split移到同一行。

    try {
        int row = 0, col = 0;
    
        // changed == null to != null
        while ((line = b.readLine()) != null) {
            String[] s = line.split("|", 4);
    
            tableData[row][0] = s[0];
            tableData[row][1] = s[1];
            tableData[row][2] = s[2];
            tableData[row][3] = s[3];
    
            row++;
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
  9. 试试吧。

答案 3 :(得分:0)

  

仅显示表格中最后输入的行而不是初始行。

这是因为你在while循环之外添加了行。在行++之后移动“}”。

答案 4 :(得分:0)

你有

String tableData[][]= new String[ce=counter+1][10];

其中counter = 0.所以你有足够的空间用于1而且只有1行。

后来你读了多行,所以程序得到一个ArrayOutOfBoundException。

如果您不知道提前有多少元素,我建议您使用List。