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

  • 相关阅读:
    js上传超大文件解决方案
    java上传超大文件解决方案
    jsp上传超大文件解决方案
    .net上传超大文件解决方案
    asp.net上传超大文件解决方案
    PHP上传超大文件解决方案
    内网大文件传输断点续传源码
    HDU
    Android中makfile的随记
    android 阿拉伯语下,图库中编辑运动轨迹图片,动画中会显示绿色的图片
  • 原文地址:https://www.cnblogs.com/linlf03/p/10927647.html
Copyright © 2011-2022 走看看