随机存取文件流
随机存取文件流介绍
- RandomAccessFile声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput两个接口,也就意味着这个类即可以读也可以写。
- RandomAccessFile类支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读、写文件。
- 支持只访问文件的部分内容
- 可以向已存在的文件后追加内容
- RandomAccessFile对象包含一个记录指针,泳衣标示当前读写处的位置。
- RandomAccessFile类对象可以自由移动记录指针:
- long getFilePointer():获取文件记录指针的当前位置
- void seek(long pos):将文件记录指针定位到pos位置
RandomAccessFile类
-
构造器
-
public RandomAccessFile(File file,String mode)
-
public RandomAccessFile(String name,String mode)
-
public RandomAccessFile(String name, String mode) throws FileNotFoundException { this(name != null ? new File(name) : null, mode); } public RandomAccessFile(File file, String mode) throws FileNotFoundException { String name = (file != null ? file.getPath() : null); int imode = -1; if (mode.equals("r")) imode = O_RDONLY; else if (mode.startsWith("rw")) { imode = O_RDWR; rw = true; if (mode.length() > 2) { if (mode.equals("rws")) imode |= O_SYNC; else if (mode.equals("rwd")) imode |= O_DSYNC; else imode = -1; } } if (imode < 0) throw new IllegalArgumentException("Illegal mode \"" + mode + "\" must be one of " + "\"r\", \"rw\", \"rws\"," + " or \"rwd\""); SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(name); if (rw) { security.checkWrite(name); } } if (name == null) { throw new NullPointerException(); } fd = new FileDescriptor(); fd.incrementAndGetUseCount(); open(name, imode); }
-
-
创建RandomAccessFile类实例需要指定一个mode参数,改参数指定RandomAccessFile的访问模式:
- r:以只读方式打开
- rw:打开以便读取和写入
- rwd:打开以便读取和写入;同步文件内容的更新
- rws:打开以便读取和写入;同步文件内容和元数据的更新
-
如果模式为只读r。则不会创建文件,而是会去读取一个已存在的文件,如果读取的文件不存在则会出现异常。如果模式为rw读写,如果文件不存在则会去创建文件,如果存在则不会创建
-
注意:JDK1.6上面写的每次write数据时,“rw”模式,数据不会立即写到硬盘中;而“rwd”,数据会被立即写入硬盘。如果写数据过程中发生异常,“rwd"模式中已被writer的数据被保存到硬盘,而”rw“则全部丢失。
RandomAccessFile使用例子
public class RandomAccessFileTest {
@Test
public void test(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("hello1.txt"),"r");
raf2 = new RandomAccessFile(new File("hello1.txt"),"rw");
String s = raf1.readLine();
System.out.println(s);
raf2.writeUTF("写入数据库");
if(true){
throw new Exception("dafasdf");
}
raf2.writeUTF("写入数据库");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
@Test
public void copy(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("Semaphore.png"),"r");
raf2 = new RandomAccessFile(new File("Semaphore1.png"),"rw");
byte[] buffer = new byte[1024];
int length;
while((length = raf1.read(buffer))!=-1){
raf2.write(buffer,0,length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}