Java RandomAccessFile class: dynamic reading of file contents
•
Java
Example 1
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
File file = new File("D:\\myJava\\words.txt"); // 指定文件路径
if (file.exists()) { // 判断文件是否存在
file.delete();
file.createNewFile();
}
} catch (IOException e) {
Sy@R_301_2354@.out.print(e);
}
}
}
RandomAccessFile raf = new RandomAccessFile(file,"rw");
String str1 = "晴天,阴天,多云,小雨,大风,中雨,小雪,雷阵雨"; // 要写入的字符串
String str2 = new String(str1.getBytes("GBK"),"ISO-8859-1"); // 编码转换
raf.writeBytes(str2); //写入文件
Sy@R_301_2354@.out.println("当前文件指针的位置:" + raf.getFilePointer());
raf.seek(6); // 移动文件指针
Sy@R_301_2354@.out.println("从文件头跳过6个字节,现在文件内容如下:");
byte[] buffer = new byte[2];
int len = 0;
while ((len = raf.read(buffer,2)) != -1) {
Sy@R_301_2354@.out.print(new String(buffer,len)); // 输出文件内容
}
当前文件指针的位置:48 从文件头跳过6个字节,现在文件内容如下: 阴天,多云,小雨,大风,中雨,小雪,雷阵雨
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
