ITeye博客

18、java随机访问RandomAccessFile类

坏我一锅粥 · 2014-03-22 21:35 · IO · 编程语言 · Java · Markdown


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

}


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。