Java读写基本数据类型,以及RAF指针的操作

Java读写基本数据类型,以及RAF指针的操作

public static void main(String[] args) throws IOException {
		RandomAccessFile raf=new RandomAccessFile("note.txt","rw");
		//获取指针位置
		long pos=raf.getFilePointer();
		System.out.println("pos:"+pos);
		
		//向文件中写入int最大值
		int max=Integer.MAX_VALUE;
		/*                             vvvvvvvv
		 * 01111111  11111111 11111111 11111111
		 * 
		 * max>>>24
		 * 
		 * 00000000  00000000 00000000 01111111
		 */
		raf.write(max>>>24);
		System.out.println("pos:"+raf.getFilePointer());
		raf.write(max>>>16);
    	raf.write(max>>>8);
		raf.write(max);
		System.out.println("pos:"+raf.getFilePointer());
		/*
		 * RAF提供了方便我们写出基本类型的相关方法
		 * 
		 * 一次性将给定的int值4个字节全部写出
		 */
		raf.writeInt(max);
		System.out.println("pos:"+raf.getFilePointer());
		raf.writeLong(123l);
		System.out.println("pos:"+raf.getFilePointer());
		raf.writeDouble(123.123);
		System.out.println("pos:"+raf.getFilePointer());
		/*
		 * void seek(long pos)
		 * 移动指针到指定位置
		 */
		raf.seek(0);
		System.out.println("pos:"+raf.getFilePointer());
		//读取EOF end of file
		int d=raf.read();
		System.out.println(d);
		System.out.println("pos:"+raf.getFilePointer());
		
		//读取long
		raf.seek(8);
		long l=raf.readLong();
		System.out.println("long:"+l);
		System.out.println("pos:"+raf.getFilePointer());
		
		double dou=raf.readDouble();
		System.out.println("double:"+dou);
		System.out.println("写出完毕");
		raf.close();
	}

你可能感兴趣的:(IT工作者)