zoukankan      html  css  js  c++  java
  • Java IO系统--RandomAccessFile

    RandomAccessFile 实现了DataOutput接口和DataInput接口。父类是Object,不继承任何的InputStream和OutStram。

    public class RandomAccessFile implements DataOutput, DataInput, Closeable{
    ...
    }
    

    代码例子

    定义一个Person类

    class Person{
    	int id;
    	String name;
    	
    	double height;
    	
    	
    	
    	
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public double getHeight() {
    		return height;
    	}
    
    	public void setHeight(double height) {
    		this.height = height;
    	}
    
    	public Person() {
    		
    	}
    
    	public Person(int id, String name, double height) {
    		
    		this.id = id;
    		this.name = name;
    		this.height = height;
    	}
    	
    	public void write(RandomAccessFile raf) throws Exception{
    		raf.writeInt(this.id);
    		raf.writeUTF(this.name);
    		raf.writeDouble(this.height);
    	}
    	
    	public void read(RandomAccessFile raf)throws Exception{
    		this.id = raf.readInt();
    		this.name = raf.readUTF();
    		this.height = raf.readDouble();
    	}
    	
    	
    }
    

      

    RandomAccessFile 使用

    public class RandomAccessFile1 {
    
    	public static void main(String[] args) throws Exception {
    		Person p = new Person(1,"Tom", 1.8);
    		RandomAccessFile raf = new RandomAccessFile("D:/temp/randomAccessFile.txt", "rw");
    		p.write(raf);
    		
    		
    		Person p2 = new Person();
    		//让读的位置重回到文件开头
    		raf.seek(0);
    		p2.read(raf);
    		
    		System.out.println(p2.getId() +" " + p2.getName() +" " +p2.getHeight());
    		
    	
    	}
    }
    

      

    “rw”,既能读又能写

    “r”,文件可读不可写

  • 相关阅读:
    网络编程2018-4-23
    网络编程
    异常处理
    在Asp.net core使用配置Json创建动态目录树
    Asp.net Core中文转换成拼音
    解决Asp.Net core 控制台出现乱码的情况
    解决Asp.net Core中chtml文档中文乱码的问题
    取代Ajax.BeginForm的ajax使用方法
    将数据库模型放入到.Net Core的类库中
    如何使用Resource资源文件
  • 原文地址:https://www.cnblogs.com/linlf03/p/10927647.html
Copyright © 2011-2022 走看看