问题遇到的现象和发生背景
这里发我想将几个基本数据类型写入文件,文件里是乱码,然后我通过DataInputStream读取的时候报了EOFException
问题相关代码,请勿粘贴截图
public static void main(String[] args) throws IOException {
String path = "src/data.txt";
String topath = "读取.txt";
DataInputStream dataInput;
DataOutputStream dataOutput;
dataOutput=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(topath))));
int i=1;
boolean flag=true;
String s="我";
double dou=3.00;
dataOutput.write(i);
dataOutput.writeBoolean(flag);
dataOutput.writeUTF(s);
dataOutput.writeDouble(dou);
dataOutput.flush();
dataOutput.close();
dataInput=new DataInputStream(new BufferedInputStream(new FileInputStream(new File(topath))));
int i1 = dataInput.readInt();
boolean b = dataInput.readBoolean();
String s1 = dataInput.readUTF();
if (s1 instanceof String){
s1=(String)s1;
}
double v = dataInput.readDouble();
System.out.println(i1);
System.out.println(b);
System.out.println(s1);
System.out.println(v);
dataInput.close();
}
运行结果及报错内容
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at com.zheng.CopyFile04.main(CopyFile04.java:37)
我的解答思路和尝试过的方法
想不明白白,来问问大嗯。
我想要达到的结果
能正确读取出文件里的内容,通过控制台输出。感谢解答!