本帖最后由 a6511631 于 2014-7-18 16:26 编辑
在毕老师的基础视频中关于IO流的部分,有专门介绍这个RandAccessFile对象的片段,并写了一个这样的例子。
附上代码:
- import java.io.*;
- public class RandromAccessFileDemo {
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- File f = new File("./Rand.txt");
- writeFile2(f);
- readFile(f);
- }
- public static void readFile(File f)throws IOException{
- RandomAccessFile raf = new RandomAccessFile(f,"r");
- raf.seek(8);
- raf.skipBytes(8);
- byte[] buf = new byte[4];
-
- while((raf.read(buf))!=-1){
-
- //将4个字节从raf中读出来存进buf
- String name= new String(buf);
- System.out.println("name="+name);
- int age = raf.readInt(); //就是读4个字节出来转换为Int
- System.out.println("age="+age);
- }
- raf.close();
- }
- public static void writeFile(File f) throws IOException{
- RandomAccessFile raf = new RandomAccessFile(f,"rw");
- raf.writeBytes("lisi");
- raf.writeInt(13);
- raf.close();
- }
- public static void writeFile2(File f) throws IOException{
- RandomAccessFile raf = new RandomAccessFile(f,"rw");
- raf.write("lisi".getBytes());
- raf.writeInt(13);
- raf.write("zhao".getBytes());
- raf.writeInt(18);
- raf.write("wang".getBytes()); //如果这里字符串长度不是4个字节,会报错
- raf.writeInt(20);
- raf.close();
- }
- }
复制代码
疑问是这样的代码示例中是这样写入的:raf.write("lisi".getBytes());但是当我这样写入时:raf.write("zhangsan".getBytes());
如果写入流在写入时,不能保证都是四个字节的字符串的话,就会输出乱码并且抛出异常。
如果将需求设为:写入时,字符串长度在8个字节内波动,那么该如何实现?
比如有个人不叫"lisi",叫"zhangsan",那要怎么才读得出来呢?
|
|