我有一个小应用程序,旨在获取双数并将它们存储到二进制文件中。然后逐个读取它们并将它们存储到一个数组中,但我无法弄清楚如何正确读取文件?
以下是代码:
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
} //听众的结尾
答案 0 :(得分:3)
如果要分别读取和写入基元类型,请使用DataInputStream和DataOutStream。 This example会让你开始。
要读取的样本,直到文件结束。请注意,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("");
}
}
}
答案 1 :(得分:2)
使用DataInputStream
从文件读取,DataOutputStream
写入文件。
为什么DataInputStream
和DataOutputStream
?
因为这些类支持已修改 Reading
中的Writing
和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();
}
注意:请确保Read
和Write
使用相同的 流 类。
答案已更新:
1)从for
循环中取出这两行。
fileOut = new FileOutputStream(fileName);
dOut = new DataOutputStream(fileOut);
2)在写入文件之前,还要检查doubleNumberArray
中存在多少元素。
3)从while循环中取出此行double d
。在while循环外定义d
,然后使用d = dIn.readDouble()
。
4)使用readArr.add(d)
代替readArr.add(index2,d)
。因为ArrayList
可以根据需要自行创建索引。