好吧,我想我被困在这里了。无法从文件中获取值以显示在JOptionPane的消息对话框中,该对话框包含在while循环中。现在我不知道输入/输出流的哪个方法用来显示这个文件上的所有数据,我认为被序列化为UTF8?
请告诉我做什么,什么东西我错过了,因为我是新的java。io类。
同样,文件StudentData。很少有人给我。并不是我不想自己做研究因为我已经做过了,我只是被困住了。我读了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");
}
}
}
while((counter=myInputStream.read()) != endOfFile)
问题可能在这里。你正在读取一个字节,然后把它扔掉。文件不太可能包含像这样的额外字节,这些字节是要被丢弃的。正确的循环应该是这样的:
try
{
for (;;)
{
// .... readUTF() etc
}
}
catch (EOFException exc)
{
// You've read to end of file.
}
// catch IOException etc.