• 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();
    		
    	}
    

      

  • 相关阅读:
    LeetCode#34 Search for a Range
    Multiplication algorithm
    LeetCode#31 Next Permutation
    Spring boot之Hello World
    spring boot 简介
    分布式-网络通信-线程
    分布式-网络通信-协议
    分布式-架构图
    9.leetcode70-climbing stairs
    8.Leetcode69 Sqrt(x) 笔记
  • 原文地址:https://www.cnblogs.com/achengmu/p/7107550.html
Copyright © 2020-2023  润新知