[英]RandomAccessFile readFully EOF exception
我使用RandomAccessFile类和read或readFully方法得到EOF异常。 我尝试读取的数据长度为1,偏移量为0,所以我不希望收到EOF异常。 我看到文件已创建并成功写入其中。
这是我的代码:
private static void createFile() {
if(pub_f != null)
{
System.out.println("file already exists");
}
try
{
pub_f = new RandomAccessFile("file.bin", "rw");
pub_f.setLength(10*1024);
}
catch (IOException e)
{
System.out.println("fail to open file. Exception message: " + e.getMessage());
e.printStackTrace();
}
if(f == null)
{
System.out.println("fail to open file");
}
else
{
System.out.println("file created");
}
//initialize file content
for(int i = 0; i<10240; i++)
{
try
{
pub_f.write(0);
}
catch (IOException e)
{
System.out.println("fail to initialize file content. Exception message: " + e.getMessage());
e.printStackTrace();
}
}
}
public int ReadFile(int offset, int length, byte[] data)
{
if (pub_f == null)
{
System.out.println("fail to open file for reading");
return -1;
}
try
{
pub_f.readFully(data, offset, length);
}
catch (IOException e)
{
System.out.println("fail to read from file. Exception message: "+ e.getMessage());
e.printStackTrace();
return -1;
}
return 0;
}
在我的主要:
int len = 1;
int offset = 0;
byte[] data = new byte[512];
createFile();
readFile(offset, len, data);
请有人帮忙找到我在这里想念的东西吗?
谢谢!
写入文件后,您忘记了seek
(设置文件指针)回到文件的开头,因此它将尝试从文件的末尾读取。 这将给您恰当地命名为EOFException
。
在读取之前添加对seek(0L)
的调用,以从文件的开头开始读取。
int len = 1;
int offset = 0;
byte[] data = new byte[512];
createFile();
pub_f.seek(0L); // <---- set the file pointer back to the start of the file.
readFile(offset, len, data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.