黑马程序员24-3: RandomAccessFile随机存取文件

[align=center]------- [url=http://edu.csdn.net/heima]android培训 [/url]、[url=http://edu.csdn.net/heima]java培训[/url]、期待与您交流!------- [/align]


package cn.itcast.io.p3.randomfile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {

/*
* RandomAccessFile
* 一看这个类名字,纠结。不是io体系中的子类。
*
* 特点:
* 1,该对象即能读,又能写。
* 2,该对象内部维护了一个byte数组,并通过指针可以操作数组中的元素,
* 3,可以通过getFilePointer方法获取指针的位置,和通过seek方法设置指针的位置。
* 4,其实该对象就是将字节输入流和输出流进行了封装。
* 5,该对象的源或者目的只能是文件。通过构造函数就可以看出。
*
*
*/

// writeFile();
// readFile();
randomWrite();
}

public static void randomWrite() throws IOException{
RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "rw");

//往指定位置写入数据。
raf.seek(3*8);

raf.write("哈哈".getBytes());
raf.writeInt(108);

raf.close();
}


public static void readFile() throws IOException {

RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "r");

//通过seek设置指针的位置。
raf.seek(1*8);//随机的读取。只要指定指针的位置即可。

byte[] buf = new byte[4];
raf.read(buf);

String name = new String(buf);

int age = raf.readInt();

System.out.println("name="+name);
System.out.println("age="+age);

System.out.println("pos:"+raf.getFilePointer());

raf.close();


}

//使用RandomAccessFile对象写入一些人员信息,比如姓名和年龄。
public static void writeFile() throws IOException{
/*
* 如果文件不存在,则创建,如果文件存在,不创建
*
*/
RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");

raf.write("张三".getBytes());
raf.writeInt(97);
raf.write("小强".getBytes());
raf.writeInt(99);
//
raf.close();
}

}




[align=center]------- [url=http://edu.csdn.net/heima]android培训 [/url]、[url=http://edu.csdn.net/heima]java培训[/url]、期待与您交流!------- [/align]

[align=center]详细请查看:[url=http://edu.csdn.net/heima]http://edu.csdn.net/heima [/url]------- [/align]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值