2

我有一个小型应用程序,旨在获取双数并将它们存储到二进制文件中。然后将它们一一读取并存储到一个数组中,但我不知道如何正确读取文件?

这是代码:

     import java.awt.*;
     import java.awt.event.ActionEvent;
     import java.awt.event.ActionListener;
     import java.io.*;
     import java.util.ArrayList;

     import net.miginfocom.swing.MigLayout;

     import javax.swing.*;


  public class Q3 extends JFrame {

private JPanel thePanel;
private JLabel lblDouble;
private JTextField txtDouble;
private JButton btnAdd, btnStore, btnRead;

ArrayList<Double> doubleNumberArray = new ArrayList<Double>();
ArrayList readArr = new ArrayList();
int index = 0;
int index2 = 0;

String fileName = "data.dat";

FileOutputStream fileOut = null;
DataOutputStream dOut = null;

FileInputStream fileIn = null;
DataInputStream dIn = null;

public static void main(String[] args) {

    new Q3();


}

public Q3() {

    this.setSize(250, 150);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    Color myColor = new Color(54, 139, 255);

    thePanel = new JPanel(new MigLayout());
    thePanel.setBackground(myColor);

    lblDouble = new JLabel("Enter a Double ");
    // Text Field
    txtDouble = new JTextField(5);
    // Buttons
    btnAdd = new JButton("Add");

    btnStore = new JButton("Store");

    btnRead = new JButton("Read File");

    ListenerForButton lForAddButton = new ListenerForButton();
    // Adding action listener to buttons
    btnAdd.addActionListener(lForAddButton);
    btnStore.addActionListener(lForAddButton);
    btnRead.addActionListener(lForAddButton);

    thePanel.add(lblDouble);
    thePanel.add(txtDouble, "wrap");
    thePanel.add(btnAdd, "skip1,split2");
    thePanel.add(btnStore, "wrap");
    thePanel.add(btnRead, "skip1");


    this.add(thePanel);
    this.setVisible(true);

}

// Implement Listener

public class ListenerForButton implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == btnAdd) {

            double convertDouble = Double.parseDouble(txtDouble.getText());
            doubleNumberArray.add(index, convertDouble);
            index++;
            txtDouble.setText("");

            System.out.print(doubleNumberArray);

        } else if (e.getSource() == btnStore) {

            for (int i = 0; i < doubleNumberArray.size(); i++) {

                try {

                    fileOut = new FileOutputStream(fileName);

                    dOut = new DataOutputStream(fileOut);

                    dOut.writeDouble(doubleNumberArray.get(i));


                } catch (Exception ex) {

                    ex.printStackTrace();

                } finally {
                    try {
                        dOut.close();


                    } catch (IOException e1) {

                        e1.printStackTrace();
                    }
                }

            } // end of loop

            //System.out.println("Done");
            doubleNumberArray.clear();// empty our array
            index = 0;

        } else if (e.getSource() == btnRead) {

            try {

                fileIn = new FileInputStream(fileName);
                dIn = new DataInputStream(fileIn);

                System.out.println("Din" + dIn.available());

                try {

                    double d ;

                    while (dIn.available() > 0) {

                        d =  dIn.readDouble();
                        readArr.add(d);



                    }

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

            } catch (Exception exception) {
                exception.printStackTrace();
            }

            System.out.print(readArr);

        }


    }// end of read button

}// action performed

}//监听器结束

4

2 回答 2

3

如果要分别读取和写入原始类型,请使用DataInputStreamDataOutStream 。这个例子会让你开始。

样本阅读直到文件结束。请注意,DataStreams 通过捕获 EOFException 来检测文件结束条件,而不是测试无效的返回值。DataInput 方法的所有实现都使用 EOFException 而不是返回值。

public class Q3 extends JFrame
{
    private final JPanel thePanel;
    private final JLabel lblDouble;
    private final JTextField txtDouble;
    private final JButton btnAdd, btnStore, btnRead;

    private final List<Double> doubleNumberArray = new ArrayList<Double>();
    private final List<Double> readArr = new ArrayList<Double>();
    private int index = 0;

    private final String fileName = "c:/home/data.dat";

    public static void main(String[] args)
    {
    new Q3();
    }

    public Q3()
    {
    this.setSize(250, 150);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    Color myColor = new Color(54, 139, 255);

    thePanel = new JPanel();
    thePanel.setBackground(myColor);

    lblDouble = new JLabel("Enter a Double ");
    // Text Field
    txtDouble = new JTextField(5);
    // Buttons
    btnAdd = new JButton("Add");
    btnStore = new JButton("Store");
    btnRead = new JButton("Read File");

    // Adding action listener to buttons
    btnAdd.addActionListener(new ListenerForButton());
    btnStore.addActionListener(new StoreButtonListener());
    btnRead.addActionListener(new ReadButtonListener());

    thePanel.add(lblDouble);
    thePanel.add(txtDouble, "wrap");
    thePanel.add(btnAdd, "skip1,split2");
    thePanel.add(btnStore, "wrap");
    thePanel.add(btnRead, "skip1");

    this.add(thePanel);
    this.setVisible(true);
    }

    public class ReadButtonListener implements ActionListener
    {
    @Override
    public void actionPerformed(ActionEvent e)
    {
        DataInputStream din = null;
        try
        {
        din = new DataInputStream(new FileInputStream(fileName));
        readArr.clear();

        while (true)
        {
            Double data = din.readDouble();
            System.out.printf("\n-> %s \n ", data);
            readArr.add(data);
        }
        }
        catch (EOFException ignore)
        {
        }
        catch (Exception ioe)
        {
        ioe.printStackTrace();
        }
        finally
        {
        if (din != null)
        {
            try
            {
            din.close();
            }
            catch (IOException e1)
            {
            e1.printStackTrace();
            }
        }
        }
    }
    }

    public class StoreButtonListener implements ActionListener
    {
    @Override
    public void actionPerformed(ActionEvent e)
    {
        DataOutputStream outFile = null;
        try
        {
        outFile = new DataOutputStream(new FileOutputStream(fileName));

        for (int i = 0; i < doubleNumberArray.size(); i++)
        {
            Double d = doubleNumberArray.get(i);
            System.out.printf("\nWriting to file %s", d);
            outFile.writeDouble(d);
        }
        }
        catch (Exception ex)
        {
        ex.printStackTrace();
        }
        finally
        {
        if (outFile != null)
        {
            try
            {
            outFile.close();
            }
            catch (IOException e1)
            {
            e1.printStackTrace();
            }
        }
        }
        doubleNumberArray.clear();// empty our array
        index = 0;
    }
    }

    public class ListenerForButton implements ActionListener
    {
    @Override
    public void actionPerformed(ActionEvent e)
    {
        double convertDouble = Double.parseDouble(txtDouble.getText());
        doubleNumberArray.add(index, convertDouble);
        index++;
        txtDouble.setText("");
    }
    }
}
于 2013-05-18T02:32:21.307 回答
2

用于DataInputStream读取文件和DataOutputStream写入文件。

为什么DataInputStreamDataOutputStream

因为这些类支持ReadingWriting修改 UTF-8中。

修改了 什么UTF-8

修改 UTF-8意味着数据将以 的形式被读取和写入Java Primitive Types。这样您就可以在文件中read / write直接处理您的java 变量

写作:

DataOutputStream out = new DataOutputStream(new FileOutputStream("MyBinaryFile.txt"));
out.writeDouble(double d);

阅读:

DataInputStream in = new DataInputStream(new FileInputStream("MyBinaryFile.txt"));
while(in.available() > 0)
{
in.readDouble();
}

注意:确保您ReadWrite使用相同的类。

答案更新:

1)for将这两行从循环中取出。

fileOut = new FileOutputStream(fileName);
dOut = new DataOutputStream(fileOut);

2)doubleNumberArray还要检查在写入文件之前存在多少元素。

3)将此行double d从while循环中取出。定义d外部 while 循环,然后使用d = dIn.readDouble().

4)使用readArr.add(d)代替readArr.add(index2,d)。因为ArrayList根据需要自行创建索引。

于 2013-05-18T02:54:41.060 回答