2015-10-22 79 views
0

好吧,我想我被困在這裏。無法從文件中獲取值以顯示在JOptionPane的消息對話框中,並在其中包含在while循環中。 現在我不知道使用哪種輸入/輸出流來顯示這個文件上的所有數據,我相信這些數據會被序列化爲UTF8?Java IO不顯示文件數據

請告訴我該怎麼做,以及由於我是新來的java.io類而錯過了什麼。

此外,文件StudentData.feu剛剛給我。這不是我不想自己研究,因爲我已經做了,我只是卡住了。我讀了Javadoc,但我現在無能爲力。

import java.io.*; 
import javax.swing.JOptionPane; 

public class MyProj { 


public void showMenu() { 
    String choice = JOptionPane.showInputDialog 
    (null, "Please enter a number: " + "\n[1] All Students" + "\n[2] BSCS Students" + "\n[3] BSIT Students" 
    + "\n[4] BSA Students" + "\n[5] First Year Students" + "\n[6] Second Year Students" + "\n[7] Third Year Students" 
    + "\n[8] Passed Students" + "\n[9] Failed Students" + "\n[0] Exit"); 

    int choiceConvertedString = Integer.parseInt(choice); 

    switch(choiceConvertedString){ 
     case 0: 
      JOptionPane.showMessageDialog(null, "Program closed!"); 
      System.exit(1); 
      break; 
    } 
} 

DataInputStream myInputStream; 
OutputStream myOutputStream; 
int endOfFile = -1; 
double grades; 
int studentNo; 
int counter; 
String studentName; 
String studentCourse; 

public void readFile() 
{ 

    try 
    { 
     myInputStream = new DataInputStream 
      (new FileInputStream("C:\\Users\\Jordan's Pc\\Documents\\NetBeansProjects\\MyProj\\StudentData.feu")); 
     try{ 

      while((counter=myInputStream.read()) != endOfFile) 
      { 

      studentName = myInputStream.readUTF(); 
      studentCourse = myInputStream.readUTF(); 
      grades = myInputStream.readDouble(); 

      JOptionPane.showMessageDialog 
      (null, "StdNo: " + studentNo + "\n" 
        + "Student Name: " + studentName + "\n" 
        + "Student Course: " + studentCourse + "\n" 
        + "Grades: " + grades); 
      } 
     } 
     catch(FileNotFoundException fnf){ 
      JOptionPane.showMessageDialog(null, "File Not Found"); 
     } 

    }/* end of try */ 

     catch(EOFException ex) 
     { 
      JOptionPane.showMessageDialog(null, "Processing Complete"); 
     } 

     catch(Exception e) 
     { 
      JOptionPane.showMessageDialog(null, "An error occured"); 
     } 

} 

}

+0

我能夠讓它顯示,但是這是我得到運行: http://picpaste.com/screenshot-CoOu1hh9.jpg – p3ace

+0

你的圖片是模糊不清。只需發佈文字。這些文件是如何產生的?用'DataOutputStream'?在一個指示符字節序列中,後跟兩個'writeUTFs()',後面跟着一個'writeDouble()'?他們真的是二元的嗎?因爲如果沒有,你的閱讀代碼不可能工作。 – EJP

+0

@EJP,文件是用你提到的write *()函數生成的。我知道,因爲我能夠顯示我猜它使用此代碼「一行」。但是,我仍然需要幫助顯示文件中的所有數據。我在使用While Loop時遇到問題。這是更新的代碼。 http://stackoverflow.com/questions/33287122/java-io-while-loop-end-of-file – p3ace

回答

0
while((counter=myInputStream.read()) != endOfFile) 

這個問題可能是在這裏。您正在讀取一個字節,然後將其丟棄。該文件不可能包含像這樣的額外字節,這些字節將被丟棄。正確的循環將是這樣的:

try 
{ 
    for (;;) 
    { 
     // .... readUTF() etc 
    } 
} 
catch (EOFException exc) 
{ 
    // You've read to end of file. 
} 
// catch IOException etc.