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”,文件可读不可写

  • 相关阅读:
    Python从入门到精通系列文章总目录
    使用465端口加密发邮件
    kubernetes学习14—Dashboard搭建和认证
    kubernetes学习01—kubernetes介绍
    CSS基础
    SVN 命令行的使用
    Python判断字符集
    Flask框架(2)-JinJa2模板
    搭建ntp服务器
    Ansible的Playbook的编写
  • 原文地址:https://www.cnblogs.com/linlf03/p/10927647.html
Copyright © 2011-2022 走看看