CYBERSIX
CYBERSIX

Reputation: 377

How to read a binary file of double numbers using Java?

I have a small application that is designed to get double numbers and store them into a binary file. Then read them all again one by one and store them into an array, but I can not figure out how to read the file properly?

Here is the code:

     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

}// end of listener

Upvotes: 2

Views: 7416

Answers (2)

Aravind Yarram
Aravind Yarram

Reputation: 80186

Use DataInputStream and DataOutStream if you want to read and write the primitive types respectively. This example will get you started.

Sample to read until end of file. Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.

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("");
    }
    }
}

Upvotes: 3

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

Use DataInputStream to read from file and DataOutputStream to write to file.

Why DataInputStream and DataOutputStream ?

Because these classes support Reading and Writing in modified UTF-8.

What is modified UTF-8 ?

Modified UTF-8 means Data will be read and written in the form of Java Primitive Types. so that you can read / write straight your java variables in the file.

Writing:

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

Reading:

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

Note: Make sure you Read and Write using same stream classes.

Answer Updated:

1) Take out these 2 lines out of for loop.

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

2) Also check how many elements exist in doubleNumberArray before writing to file.

3) Take this line double d out of while loop. Define d outside while loop and then use d = dIn.readDouble().

4) Use readArr.add(d) instead of readArr.add(index2,d). Because ArrayList creates indexes on its own as you require.

Upvotes: 2

Related Questions