您的位置:首页 > 编程语言 > Java开发

18、java随机访问RandomAccessFile类

2014-03-22 21:35 288 查看

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;
}

}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: