黑马程序员技术交流社区
标题:
RandomAccessFile流的一个问题
[打印本页]
作者:
刘凯
时间:
2013-2-23 17:08
标题:
RandomAccessFile流的一个问题
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流 不能够再一次执行中 对同一个文件 写和读 都执行么?
求高手解答
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2