日期:2014-05-16  浏览次数:20903 次

java RandomAccessFile随机读取文件内容
public class TestRandom {
	public static void main(String[] args) throws Exception {
		typeTextByRandom("data/data1.txt");
	}

	public static void typeTextByRandom(String fileName) {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(fileName, "r");
			raf.seek(new Random().nextInt(100)*2);
			byte[] bytes = new byte[30];
			while (raf.read(bytes) != -1) {
				System.out.println(new String(bytes,"gbk"));
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e1) {
				}
			}
		}

	}
}

?注:data1.txt为中文内容即可,文件编码设为gbk,即将文件打开,另存为保存时,在编码一栏选择ANSI编码。