import java.io.*;
class RandomAccessTest
{
public static void main(String[] args)
{
RandomAccessFile raf = null;
try
{
raf = new RandomAccessFile("Test.txt","rw");
write(raf);
read(raf);
}
catch (Exception ioe)
{
throw new RuntimeException("初始化失败");
}
finally
{
try
{
if(raf!=null)
raf.close();
}
catch (IOException ioe)
{
throw new RuntimeException("读写流关闭失败");
}
}
}
public static void write(RandomAccessFile raf)
{
try
{
raf.write("张三".getBytes());
raf.writeInt(33);
raf.writeChar('男');
raf.write("李四".getBytes());
raf.writeInt(33);
raf.writeChar('男');
}
catch (IOException ioe)
{
throw new RuntimeException("写失败");
}
}
public static void read(RandomAccessFile raf)
{
try
{
byte[] buf = new byte[4];
raf.seek(10);
raf.read(buf);
String name = new String(buf);
int age = raf.readInt();
char sex = raf.readChar();
System.out.println("姓名:"+name+" 年龄:"+age+"性别:"+sex);
}
catch (IOException ioe)
{
throw new RuntimeException("读失败");
}
}
}
程序报异常 : 读失败
然而将上面代码红色标记的
write(raf);
read(raf);
注释read(raf);编译执行一遍 先写入
再注释write(raf);编译再执行 读出
就没问题
这是在说
一个RandomAccessFile流 不能够再一次执行中 对同一个文件 写和读 都执行么?
求高手解答
|
|