package inputDemo;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException{
RandomAccessFile raf= new RandomAccessFile("E://file.txt","rw");
//获取指针当前位置,默认为文件的第一个字节,是0.
long pos = raf.getFilePointer();
System.out.println(pos);//0
int imax = Integer.MAX_VALUE;
/*
* 将int值写入文件
* 01111111 11111111 11111111 11111111
* vvvvvvvv
* 01111111 11111111 11111111 11111111
*
* 位移操作
* imax>>>24
* raf.write(imax>>>24);将最高8位移动到最低8位
* raf.write(imax>>>16);
* raf.write(imax>>>8);
* raf.write(imax);
*/
raf.writeInt(imax);
/*
* 由此看出,当我们调用writeInt方法后,指针向后
* 移动了4个字节,这说明RandomAccessFile总是
* 在指针当前位置进行读写操作的,并且操作完毕后
* 指针会自动向后移动。
*/
System.out.println(raf.getFilePointer());
raf.writeLong(123L);
System.out.println(raf.getFilePointer());
raf.writeDouble(123.123);
System.out.println(raf.getFilePointer());
/*
* 若想从文件最开始出读取int值,我们需要将
* 指针移动到文件最开始
*
* void seek(long pos)
* 该方法用来将指针移动到指定位置
*/
raf.seek(0);
System.out.println(raf.getFilePointer());
/*
* 连续读取4个字节并转换为int值返回
* 若发现在文件末尾尝试读取,那么该方法
* 会抛出异常
*/
int i = raf.readInt();
System.out.println(i);
//读取double
// raf.seek(12);
// double d = raf.readDouble();
// System.out.println(d);
/*
* void skipBytes(int l)
* 在指针当前位置出开始,连续跳过给定的字节量
*/
raf.skipBytes(8);
double d = raf.readDouble();
System.out.println(d);
raf.close();
}
}
RandomAccessFile
最新推荐文章于 2024-07-15 22:55:18 发布