您的位置:首页 > 编程语言 > Java开发

java:RandomAccessFile(随机读写文件)

2017-02-26 23:10 429 查看
文件的存在形式及读写(RandomAccessFile )
文件是以byte,byte,byte字节形式存在的。
RandomAccessFile 支持读写文件,支持随机读取任意位置的文件
(1)打开文件
第一种“rw” 第二种 “r”
RandomAccessFile a = new RandomAccessFile(file,"rw");
文件指针,打开文件时 pointer = 0,指向第一个位置,依次往后移
( 2 ) 写操作
a.write(int i) 一次写入1个字节
(3)读操作
int b = a.read() 一次读入一个字节
(4)读写操作后要关闭,否则会产生意想不到的结果(官方的提示)

package cn.java.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class FileWR {

/**
* 文件的读写操作
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File file = new File("demo");
if(!file.exists()){
file.mkdir();
}
file = new File(file, "a.txt");
if(!file.exists()){
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.writeInt(5);
raf.writeUTF("撒");
String as = "我爱你";
byte[] b  = as.getBytes("utf-8");
raf.write(b);

//指针移到首位
raf.seek(0);
//因为本来就是存储的byte,所以读取存到字节数组中
//字节长度
byte[] c = new byte[(int)raf.length()];
//内容存到字节数组中
raf.read(c);
System.out.println(Arrays.toString(c));

//字节转化为字符串
String temp = new String(c, "utf-8");
System.out.println(temp);
raf.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: