永发信息网

java中文件输入输出的问题

答案:2  悬赏:50  手机版
解决时间 2021-05-02 01:51
  • 提问者网友:刺鸟
  • 2021-05-01 02:48
源代码: import java.io.*; class Test2{ public static void main(String[] args)throws Exception{ RandomAccessFile rfa=new RandomAccessFile("1.txt","rw"); Student s1=new Student(1,"zhangsan",99.8); Student s2=new Student(2,"lisi",95.0); Student s3=new Student(3,"wangwu",88.5); s1.putter(rfa); s2.putter(rfa); s3.putter(rfa); Student s=new Student(); rfa.seek(0); for(long i=0;i<rfa.length();i=rfa.getFilePointer()){ s.getter(rfa); System.out.println(s.num+":"+s.name+":"+s.sorce); } rfa.close(); } } class Student{ int num; double sorce; String name; Student(){ } Student(int num,String name,double sorce){ this.num=num; this.name=name; this.sorce=sorce; } public void putter(RandomAccessFile rtf) throws IOException{ rtf.writeInt(num); rtf.writeUTF(name); rtf.writeDouble(sorce); } public void getter(RandomAccessFile rtf) throws IOException{ num=rtf.readInt(); name=rtf.readUTF(); sorce=rtf.readDouble(); } } 为什么执行后还有这样的错误出来: 1:zhangsan:99.8 2:lisi:95.0 3:wangwu:88.5 Exception in thread "main" java.io.EOFException at java.io.RandomAccessFile.readUnsignedShort(RandomAccessFile.java:656) at java.io.DataInputStream.readUTF(DataInputStream.java:545) at java.io.RandomAccessFile.readUTF(RandomAccessFile.java:875) at Student.getter(Test2.java:46) at Test2.main(Test2.java:17) 麻烦哪位高手指点一下。
最佳答案
  • 五星知识达人网友:一叶十三刺
  • 2021-05-01 03:50
你的代码我再eclipse 3.4.2 + jdk1.5.0_21上执行没有任何问题
也没见抛出异常,是不是版本的问题?
全部回答
  • 1楼网友:毛毛
  • 2021-05-01 05:00

我用1.5.0_20试过,也没有复制出您遇到的问题。查了一下,2007年之前的Java版本,当所需要读的bytes还没有读够但就已经到了文件末端(end-of-file)的时候就会抛出EOFException。我想如果您换一下您的Java版本应该就可以避免这个问题出现。以下是Reference:

http://www.docjar.com/html/api/java/io/RandomAccessFile.java.html

47 * It is generally true of all the reading routines in this class that 48 * if end-of-file is reached before the desired number of bytes has been 49 * read, an <code>EOFException</code> (which is a kind of 50 * <code>IOException</code>) is thrown. If any byte cannot be read for 51 * any reason other than end-of-file, an <code>IOException</code> other 52 * than <code>EOFException</code> is thrown. In particular, an 53 * <code>IOException</code> may be thrown if the stream has been closed. 54 *

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯