18、javaランダムアクセスRandomAccessFileクラス
1745 ワード
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;
}
}