18、java随机访问RandomAccessFile类


package com.tij.io.file;

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

/**
* 随机访问文件
* @author GYJ
* @date 2014-3-22
*/
public class RandomAccessFileExample {

/**
* RandomAccessFile类可以随机的读取写入内容进其他文件
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String fileName = "/Users/GYJ/java1.txt";
//从文件中读取指定位置的内容
System.out.println(new String(reandCharsFromFile(fileName, 10, 3)));
//把内容插入文件中指定位置
writeData(fileName, "hehe", 5);
}

/**
* RandomAccessFile写入文件
* @param fileName 路径
* @param data 内容
* @param seek 指定位置
* @throws IOException
*/
private static void writeData(String fileName, String data, int seek) throws IOException {
//'rw' r:read, w:write
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.seek(seek);
file.write(data.getBytes());
file.close();
}

/**
*
* @param fileName 文件路径
* @param seek 指定位置
* @param chars 字符串大小
* @return
* @throws IOException
*/
private static byte[] reandCharsFromFile(String fileName, int seek, int chars) throws IOException {
//'r' read
RandomAccessFile file= new RandomAccessFile(fileName, "r");
//读取位置
file.seek(seek);
//设置需要读取的字节
byte[] bytes = new byte[chars];
//开始读取
file.read(bytes);
file.close();
return bytes;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值