1、java.io,File类用于表示文件(目录)
File类只用于表示文件(目录)的信息(名称、大小等),不能用于文件内容的访问。
2、RandomAccessFile java提供的对文件内容的访问,既可以读文件,亦可以写文件,RandomAccessFile支持随机访问文件,可以访问文件的任意位置,
a、java文件模型
在硬盘上的文件是byte byte byte存储的,是数据的集合。
b、打开文件
有两种模式“rw”(读写)、“r”(只读)
RandomAccessFile raf = new RandomeAccessFile(file,"rw");
文件指针,打开文件时指针在开头pointer = 0;
c、写方法
raf.write(int)------>只写一个字节(后8位),同时指针指向下一个位置,准备再次写入。
d、读方法
int b = raf.read();------->读一个字节
e、文件读写完成后一定要关闭
实例:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
public class FileDemo{
public static void main(String[] strs) throws IOException {
File file = new File("demo");
if(!file.exists())
file.mkdir();
File file1 = new File("raf.dat");
if (!file1.exists()) {
file1.createNewFile();
}
RandomAccessFile raFile= new RandomAccessFile(file1, "rw");
System.out.println(raFile.getFilePointer());
raFile.write('A');//只写了一个字节
System.out.println(raFile.getFilePointer());
// raFile.write('B');
int i = 0x7fffffff;
//用write方法每次只能写一个字节,如果把i写进去就得写4次
raFile.write(i>>>24);//高八位
raFile.write(i>>>16);
raFile.write(i>>>8);
raFile.write(i);
//可以直接写一个int
raFile.writeInt(i);
System.out.println(raFile.getFilePointer());
String string ="中";
byte[] bytes = string.getBytes();
raFile.write(bytes);//写了两个字节,因为是byte数组。默认是gbk编码,且该编码方式一个中文表示两个字节。
System.out.println(raFile.getFilePointer());
System.out.println(raFile.length());;
//读文件,必须把指针移到头部
raFile.seek(0);
//一次性读取,把文件中的内容都读到字节数组中。
byte[] bytes2 = new byte[(int)raFile.length()];
raFile.read(bytes2);
System.out.println(Arrays.toString(bytes2));
System.out.println(Arrays.toString(bytes2).length());
}
}
0
1
9
11
11
[65, 127, -1, -1, -1, 127, -1, -1, -1, -42, -48]
48
tip:
File file2 = new File("D:\\java包\\test.txt");
if(!file2.exists())
file2.createNewFile();
上式中的路径如果是”D\\.test.txt“,就不行,必须再来一个文件夹,不知为何。