import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* java.io.RandomAccessFile
* 用来读写文件数据
* RAF是基于指针进行读写,即,
* RAF总是在指针指向的位置读写字节,
* 并且读写后指针会向后移动
* @author Administrator
*RAF既可以读写文件数据也可以向文件中写入数据
*
*/
public class p8 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file=new File("d:/hellofeng.txt");
/*
* 第一个参数既可以是File对象
* 也可以是路径
* 第二个参数为模式:常用的有
* r:只读模式
* rw:读写模式
*/
RandomAccessFile raf
=new RandomAccessFile(file, "rw");
/*
* void wtite(int d)
* 写入给定的int值对应的二进制低八位对应的字符
*
*/
raf.write(97);
raf.close();//必须关闭,第一耗资源,第二指向最后一位,读取不到输入的数据
/*
* int read()
* 读取一个字节,并以10进制的int型返回
* 若返回值为-1,则表示读取到了文件末尾
*/
RandomAccessFile raf2
=new RandomAccessFile(file, "rw");
int d=raf2.read();
System.out.println(d);
raf.close();
/*
* 复制文件
*/
RandomAccessFile raf3
=new RandomAccessFile("d:/h.mp3", "r");
RandomAccessFile raf4
=new RandomAccessFile("d:/h213.mp3", "rw");
int d1;
long c=System.currentTimeMillis();
while ((d1=raf3.read())!=-1) {
raf4.write(d1);
}
System.out.println(System.currentTimeMillis()-c);
raf3.close();
raf4.close();
System.out.println("ok");
/**
* 若想提高读写的效率,可以通过提高每次读写的数据量
* 来减少读写的次数
*/
RandomAccessFile raf5
=new RandomAccessFile("d:/h.mp3", "r");
RandomAccessFile raf6
=new RandomAccessFile("d:/h214.mp3", "rw");
/*
* int read(byte[] data)
* 一次性尝试读取给定的字节数组总
* 长度的字节量并存入该数组中,
* 返回值为实际读取到的字节量,
* 若返回值为-1,则表示本次没有读取到
* 任何数据
*/
int len;
byte[] b=new byte[1024*10];//一次取10K
while ((len=raf5.read(b))!=-1) {
System.out.println(len);
/*含头不含尾,
* 还有不应该写成write(b)
* 因为要写入的文件的大小不一定是10K的整数倍
*/
raf6.write(b, 0, len);
}
}
}
文件的读取
最新推荐文章于 2022-08-01 11:02:53 发布