Java核心API之RandomAccessFile使用介绍

2025-05-23 08:42:01

1、RandomAccessFile的构造方法RandomAccessFile在文件随机访问操作时有两种模式,分别是只读模式和缥熹嵛郦读写模式两种。在这里提供两种RandomAccessFile类构造方法,RandomAccessFile(File file ,String mode)和RandomAccessFile(String filename, String mode),第一个参数是需要访问的文件,第二个参数是访问模式。只读模式代码如下:/* * 只读模式 * RandomAccessFile(File file,String mode) * RandomAccessFile(String filename,String mode) * RandomAccessFile构造方法第一个参数是要访问的文件, * 第二个参数是访问模式,"r"表示只读模式 */ @Test public void testReadMode() throws FileNotFoundException{ File file = new File("test.txt"); String filename = "test.txt"; RandomAccessFile raf = new RandomAccessFile(file,"r"); RandomAccessFile raf2 = new RandomAccessFile(filename,"r"); }注意:在只读模式下,若要访问的文件不存在则会抛出FileNotFoundException异常。

Java核心API之RandomAccessFile使用介绍

4、RandomAccessFile写方法代码如下: /* * read()方法,该方法读取字节的方法 ,该方法读取一个byte(8位)填充到int * 的低八位,高24位为0,返回值范围在0~255,如果返回-1表示读到了文 * 件末尾。 */ @Test public void testRead() throws IOException{ RandomAccessFile raf = new RandomAccessFile("test.txt","rw"); int d = -1; while((d=raf.read())!=-1){ System.out.println(d); } }分析:read()方法读取一个字节(8位)填充到int的低八位,所以返回值高24位为0,返回范围在0~255之间,如果返回-1表示读到了文件末尾。

5、RandomAccessFile的read(byte[] b)方法示例代码如下:/* * read(byte[] b)可以从文件中批量读取字节的方法 * 该方法会从文件中尝试最多读取给定数组的总长度的字节量, * 并从给定的字节数组第一个位置开始,将读取到的字节顺序存放至数组中, * 返回值为实际读取到的字节量 */@Test public void testReadByByteArray() throws IOException{ RandomAccessFile raf = new RandomAccessFile("test.txt","rw"); RandomAccessFile raf2 = new RandomAccessFile("test_copy.txt","rw"); byte[] b = new byte[1024*10]; int len = -1; while((len=raf2.read(b))!=-1){ raf.write(b,0,len); } }分析:read(byte[] b)批量读取字节,参数是字节数组,即批量读取字节的数据,通俗讲就是该方法读取这么多字节数组所能装下的数据。字节数组的长度一般创建为1024*10,即为10K,这样JVM能够以最佳性能读取文件内容。

Java核心API之RandomAccessFile使用介绍

8、RandomAccessFile的seek()方法代码如下: /* * void seek(long pos) * 该方法用于移动指针位置 */ @Test public void testSeek() throws IOException{ RandomAccessFile raf = new RandomAccessFile("test.txt","rw"); System.out.println(raf.getFilePointer());//0 raf.writeInt(1); System.out.println(raf.getFilePointer());//4 raf.seek(0); System.out.println(raf.getFilePointer());//0 }该方法可以移动指针到任意位置,读取数据就是这么任性,不服不行。

Java核心API之RandomAccessFile使用介绍

9、RandomAccessFile的close()方法RandomAccessFile文件访问结束后,别忘记用close()方法释放资源,作为一名环保卫士,节约能源人人有责。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢