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编码。
本文介绍了如何使用Java语言通过随机访问文件的方式读取GBK编码的文本文件,并逐行打印其内容。代码示例中展示了如何创建随机访问文件流、定位文件指针、读取文件数据并使用GBK编码解析输出。
1352

被折叠的 条评论
为什么被折叠?



