java随机读取文件的内容

来源:互联网 发布:js 24小时时间插件 编辑:程序博客网 时间:2024/05/01 18:48

package com.wj.RandomAccessFile;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo1 {

    public static void main(String[] args) {
        
        //writeFile();
        
        //readFile();
        
    }

    private static void readFile() throws FileNotFoundException, IOException {
        RandomAccessFile raf = new RandomAccessFile("d:\\test.txt", "r");
        //调整指针
        //raf.seek(8*1);
        
        //跳过指定字节数
        raf.skipBytes(8);
        
        byte [] buf = new byte[4];
        raf.read(buf);
        String name = new String(buf);
        int age = raf.readInt();
        
        System.out.println("name:" + name + " age:" + age);
        
        raf.close();
    }

    private static void writeFile() throws FileNotFoundException, IOException {
        RandomAccessFile raf = new RandomAccessFile("d:\\test.txt", "rw");
        
        raf.write("lisi".getBytes());
        raf.writeInt(98);
        raf.writeInt(258);
        
        raf.close();
    }

}


0 0