二重の数値を取得してバイナリ ファイルに格納するように設計された小さなアプリケーションがあります。次に、それらをすべて再度1つずつ読み取り、配列に格納しますが、ファイルを適切に読み取る方法がわかりませんか?
コードは次のとおりです。
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
}// リスナーの終わり