2013-05-18 80 views
2

我有一個小應用程序,旨在獲得雙數並將它們存儲到二進制文件中。然後再逐一讀取它們並將它們存儲到數組中,但我無法弄清楚如何正確讀取文件?如何使用Java讀取雙數的二進制文件?

下面是代碼:

 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會讓你開始。

取樣直到文件結束。請注意,DataStream通過捕獲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(""); 
    } 
    } 
} 
+0

如何添加讀入到arraylist? – CYBERSIX

+0

sir,'in.available()> 0'比捕捉異常要好。 –

+0

@RaviTrivedi available()不適用於DataInputStream。我建議你閱讀這個http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html –

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)取出這些2行出for循環。

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

2)還要檢查有多少元素在doubleNumberArray存在寫入文件之前。

3)取這條線double d out of while循環。在while循環外定義d,然後使用d = dIn.readDouble()

4)使用readArr.add(d)而不是readArr.add(index2,d)。因爲ArrayList會根據您的需要自行創建索引。