㈠ RandomAccessFile类:可以读写文件的内容,文本文件和其它类型文件都可以读写。
注意:读写完毕后,要关闭RandomAccessFile释放对文件的操作,以及资源。通常涉及到IO的操作,都应当捕获异常。
㈡ RandomAccessFile的读写数据方法
① 创建RandomAccessFile的实例:
RandomAccessFile raf = new RandomAccessFile(File file,"rw");
参数1:要进行读写的操作的文件对象
参数2:读写模式。"rw" : 读写。"r" : 只读
注意:创建实例时,文件不存在,则会自动创建一个文件。文件存在,且文件中原来有内容,若执行写操作,则是从文件头开始覆盖内容。
② 写操作
write(int d); 向文件中写入一个字节.注意:写入的是给定的int值的"低8位"二进制。
writeInt(int a); 写基本类型数据, 连续写4个字节,将给定的int值写入文件。
writeLong(long l);
write(byte[] b);将数组中的所有字节写入文件
write(byte[] b ,int offset,int len);从字节数组中offset出开始,连续写len个字节到文件中
③ 读取数据
int read(); 读取一个字节,以int形式返回。
注意:这个int值只有低8位有效,若返回值为-1.说明读取到了文件的末尾
int read(byte[] b); 一次性试图读取给定数组总长度的字节量,并存入数组,返回值为实际读取到的字节数。
long getFilePointer():返回当前游标所在的位置。
seek(long):将游标人为移动到某个字节位置。
注意:RandomAccessFile是基于游标进行读写操作的,总是读取或者写入游标指定的位置。所以,当我们连续写完后,游标指向的就是文件末尾。这时候试图读取其它地方的值,则会引发EOFException。我们要将游标移动到文件开始后再进行读取。
int readInt():一次读取4个字节,并还原为int值并返回
long readLong()
double readDouble()
㈢ 复制文件代码示例
public class CopyPicture
{
public static void main(String[] args)
{
File file = new File("src.jpg");
try
{
copyPicture(file);
} catch (IOException e)
{
e.printStackTrace();
}
}
static void copyPicture(File file) throws IOException
{
RandomAccessFile scrAccessFile = null;
RandomAccessFile desAccessFile = null;
try
{
scrAccessFile = new RandomAccessFile(file, "rw");
desAccessFile = new RandomAccessFile("des.jpg", "rw");
byte[] temp = new byte[1024];
// int i = randomAccessFile.read(temp);
// while (i > 0)
// {
// randomAccessFile2.write(temp);
// i = randomAccessFile.read(temp);
// }
int length = 0;
while ((length = scrAccessFile.read(temp)) > 0)
{
desAccessFile.write(temp, 0, length);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
scrAccessFile.close();
desAccessFile.close();
}
}
}