详细 代码如下 ,请各位老大帮小弟看看
package src;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class DataInputStreamTest {
public static void main(String[] args) throws Exception{
String fname = "D:\\Myworkspace\\IOTest\\src\\student.txt";
new Student("dawei").save(fname);
new Student("zhengyuan").save(fname);
Student.display(fname);
}
}
class Student{
static int count = 0;
int number = 1;
String name;
Student(){
this("");
}
Student(String name){
this.count++;
this.number = this.count;
this.name = name;
}
// 保存 数据
public void save(String fname)throws Exception{
File f = new File(fname);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(fname,true);
DataOutputStream dout = new DataOutputStream(fo);
dout.writeInt(this.number);
dout.writeChar('\t');
dout.writeChars(this.name);
dout.writeChar('\n');
dout.close();
}
// 显示数据
public static void display(String fname)throws Exception{
FileInputStream fi = new FileInputStream(fname);
DataInputStream dfi = new DataInputStream(fi);
int i = dfi.readInt();
while(i!=-1){
System.out.println("i="+i);
char ch;
while ((ch = dfi.readChar())!= '\n'){ // 这句话报出异常
System.out.println(ch);
i = dfi.readInt();
}
}
dfi.close();
}
}
------解决方案--------------------
EOF:end of file
应该是你的while的判断条件的问题。
\n可能不行吧。换成\r\n看看
------解决方案--------------------
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class DataInputStreamTest {
public static void main(String[] args) throws Exception{
String fname = "D:\\student.txt";
new Student("dawei").save(fname);
new Student("zhengyuan").save(fname);
Student.display(fname);
}
}
class Student{
static int count = 0;
int number = 1;
String name;
Student(){
this("");
}
Student(String name){
this.count++;
this.number = this.count;
this.name = name;
}
// 保存 数据
public void save(String fname)throws Exception{
File f = new File(fname);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(fname,true);
DataOutputStream dout = new DataOutputStream(fo);
dout.writeInt(this.number);
dout.writeChar( '\t');
dout.writeUTF(this.name);
dout.writeChar( '\n');
dout.close();
}
// 显示数据
public static void display(String fname)throws Exception{
FileInputStream fi = new FileInputStream(fname);
DataInputStream dfi = new DataInputStream(fi);
int i = dfi.readInt();
while(i!=-1){
System.out.print(dfi.readChar());
System.out.print(dfi.readUTF());
System.out.print(dfi.readChar());
try{
i = dfi.readInt();
}catch(Exception e){
break;
}
}
dfi.close();
}
}
------解决方案--------------------