public class RandomAccessFile extends Objectimplements DataOutput, DataInput, Closeable{...}
@Test
public void test01() throws IOException{
//读写模式
RandomAccessFile r=new RandomAccessFile(new File(""),"rw" );
//只读模式
//<span style="font-family:Arial, Helvetica, sans-serif;">RandomAccessFile r=new RandomAccessFile(new File(""),"r" );</span>
r.write(1);//写出一个字节,写出的是int值的低8位
r.close();
r.read();//每次读一个字节,填充到int的低八位
}
@Test
public void testWrite() throws IOException{
RandomAccessFile file=new RandomAccessFile(new File("emp.txt"),"rw");
file.write(97);//0110 0001
file.write(98);//0110 0010
file.write(99);//0110 0011
}
/**
* RandomAccessFile:基于指针读写,总是在指针当前位置读写,无论读写,指针都会向后移动
* RandomAccessFile总是在指针当前位置进行读写字节,并且无论进行了读还是写一个字节后,
* 指针都会自动向后移动到下一个字节的位置
* 默认创建出来RandomAccessFile时,指针位置为0,即:文件的第一个字节的位置
* @author zc
*/
public class T13RandomAccessFile {
public static void main(String[] args) throws IOException {
RandomAccessFile raf=new RandomAccessFile(new File("emp.txt"),"rw");
int a=255;
//虽然能写入,但是在记事本中打开仍是乱码字符
raf.write(a>>>24);//11111111
raf.write(a>>>16);
raf.write(a>>>8);
raf.write(a);
//获取当前指针位置
long pos=raf.getFilePointer();
//!!注意,返回值是字节4,前面写入的四个字节对应从0--3字节
System.out.println("pos:"+pos);//4
//将int值分成四部分,写入
raf.writeInt(255);
System.out.println("pos:"+raf.getFilePointer());//8
raf.writeLong(255);//long八个字节
System.out.println("pos:"+raf.getFilePointer());//16
raf.writeFloat(8);//float四个字节
System.out.println("pos:"+raf.getFilePointer());//20
raf.writeDouble(12.1);//double八个字节
System.out.println("pos:"+raf.getFilePointer());//28
raf.write(new byte[]{1,1});
raf.writeBoolean(false);
raf.writeChar(1);
//此时已经写完,指针指向文件某位
System.out.println(raf.read());//-1
/*
*void seek(long pos)
*将指针移动到指定位置
* */
raf.seek(0);
System.out.println("point:"+raf.getFilePointer());//0
//读取刚刚写入的long值
raf.seek(8);
long l=raf.readLong();
System.out.println("读出的long值:"+l);//255
//读取刚刚写入的double值
raf.seek(20);
System.out.println(raf.readDouble());//12.1
raf.close();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有