java:RandomAccessFile随机读取文件内容

RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件。

RandomAccessFile不属于InputStream和OutputStream类系的。

 

public static void main(String args[]) throws Exception
	{
		File file = new File("F:"+File.separator+"work"+File.separator+"60"+File.separator+"60.txt");		
		String s = args[0];
		if(s.equals("w"))
		{			
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			write(raf);
		}else if(s.equals("r")){		
			RandomAccessFile raf = new RandomAccessFile(file, "r");
			read(raf);
		}
		
	}
	
	//随机写
	public static void write(RandomAccessFile raf) throws Exception
	{
		String n = "zhangsan"; //8个字节
		int age = 29;          //4个字节
		raf.writeBytes(n);	
		raf.writeInt(age);
		
		n = "lisi"; //4个字节
		age = 33;      //4个字节
		raf.writeBytes(n);
		raf.writeInt(age);
		
		n="wangwu";
		age = 40;
		raf.writeBytes(n);
		raf.writeInt(age);
		
		raf.close();
		
	}
	
	//随机读
	public static void read(RandomAccessFile raf) throws Exception
	{
		byte b[] = null;
		String name = null;
		int age = 0;
		
		
		b = new byte[8];		
		raf.skipBytes(8);
		
		System.out.println("这是第二个人的信息");
		
		for(int i = 0; i< 8; i++)
		{
			b[i] = raf.readByte(); //读取字符
		}
		age = raf.readInt(); //读取字符
		
		System.out.println("姓名:"  + new String(b));
		System.out.println("年龄:" + age);
		
		raf.close();
		
	}

  

 

posted @ 2017-07-02 22:31  穆晟铭  阅读(626)  评论(0编辑  收藏  举报