输入和输出--RandomAccessFile类

RandomAccessFile 类
RandomAccessFile 类既可以读取文件内容,也可以向文件输出数据。
RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读写文件。所以说RandomAccessFile是IO流体系中功能最丰富的类。如果我们希望只访问文件的一部分内容,而不是把文件从头读到尾,使用这个类将是一个很好的选择。好多的多线程,断点的网络下载工具就是通过这个类来实现的,所有的下载工具在下载开始后都会建立2个文件:1个是与被下载文件大小相同的空文件,1个用来记录文件指针的位置。

RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile 类对象可以自由移动记录指针,常用如下2个方法:
long getFilePointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置
创建 RandomAccessFile 类可以指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
r: 以只读方式打开。rw:以读、写方式打开。另外2种:rws和rwd不怎么使用。


import java.io.IOException;
import java.io.RandomAccessFile;

public class Linkin
{

	public static void main(String[] args) throws IOException
	{
		RandomAccessFile raf = null;
		try
		{
			raf = new RandomAccessFile("src/Linkin.java", "r");
			// 获取RandomAccessFile对象文件指针的位置,初始位置是0
			System.out.println("RandomAccessFile的文件指针的初始位置:" + raf.getFilePointer());
			// 移动raf的文件记录指针的位置
			raf.seek(300);
			byte[] bbuf = new byte[1024];
			// 用于保存实际读取的字节数
			int hasRead = 0;
			// 使用循环来重复“取水”过程
			while ((hasRead = raf.read(bbuf)) > 0)
			{
				// 取出“竹筒”中水滴(字节),将字节数组转换成字符串输入!
				System.out.print(new String(bbuf, 0, hasRead));
			}
		}
		catch (Exception ioe)
		{
			ioe.printStackTrace();
		}
		finally
		{
			if (raf != null)
			{
				raf.close();
			}
		}
	}
}

import java.io.*;

public class AppendContent
{
	public static void main(String[] args) 
	{
		try(
			//以读、写方式打开一个RandomAccessFile对象
			RandomAccessFile raf = new RandomAccessFile("out.txt" , "rw"))
		{
			//将记录指针移动到out.txt文件的最后
			raf.seek(raf.length());
			raf.write("追加的内容!
".getBytes());
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
	}
}


import java.io.*;

public class InsertContent
{
	public static void insert(String fileName , long pos
		, String insertContent) throws IOException
	{
		File tmp = File.createTempFile("tmp" , null);
		tmp.deleteOnExit();
		try(
			RandomAccessFile raf = new RandomAccessFile(fileName , "rw");
			// 创建一个临时文件来保存插入点后的数据
			FileOutputStream tmpOut = new FileOutputStream(tmp);
			FileInputStream tmpIn = new FileInputStream(tmp))
		{
			raf.seek(pos);
			// ------下面代码将插入点后的内容读入临时文件中保存------
			byte[] bbuf = new byte[64];
			// 用于保存实际读取的字节数
			int hasRead = 0;
			// 使用循环方式读取插入点后的数据
			while ((hasRead = raf.read(bbuf)) > 0 )
			{
				// 将读取的数据写入临时文件
				tmpOut.write(bbuf , 0 , hasRead);
			}
			// ----------下面代码插入内容----------
			// 把文件记录指针重新定位到pos位置
			raf.seek(pos);
			// 追加需要插入的内容
			raf.write(insertContent.getBytes());
			// 追加临时文件中的内容
			while ((hasRead = tmpIn.read(bbuf)) > 0 )
			{
				raf.write(bbuf , 0 , hasRead);
			}
		}
	}
	public static void main(String[] args) 
		throws IOException
	{
		insert("InsertContent.java" , 45 , "插入的内容
");
	}
}



原文地址:https://www.cnblogs.com/LinkinPark/p/5233107.html