使用随机随机访问文件的类(RandomAccessFile)实现对指定文件内容的复制粘贴

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_44213634/article/details/98603000
RandomAccessFile类的常用方法
RandomAccessFile(File f,String mode); 使用指定的File对象和模式创建随机文件流(r/rw)
long getFilePointer() 返回以字节计算的文件偏移量(从文件开始计)作为下一个Reader和Writer的起点
long length() 返回文件中的字节数
set length() 为文件设置新长度
int read()/int read(byte[]) 从文件中读取字节数据
void seek(long pos) 设置流的偏移量(以字节为单位)
int skipBytes(int n) 跳过n个字节
write(byte[]b) 将指定的字节数写入到文件中(从当前的文件指针开始写)

File file =new File(filePath:String);

RandomAccessFile ranFile=new RandomAccessFile(file,"r/rw");

             

package RandemoAccessFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 使用RandemoAccessFile实现文件件内容的复制粘贴
 * 
 * @author 李*文
 * @version 1.8
 * @date 2019年8月6日 上午10:59:03
 * @content JAVA代码
 * @motto 代码千万条,可读第一条。代码不规范,error多两行。
 */
public class RandemoAccessFileDemo {

	public static final String filePath = "c://test/web.html";
	public static final String newFilePath = "c://test/newWeb.html";

	public static void copyAndStick() {
		File srcFile = new File(filePath);
		File newFile = new File(newFilePath);
		long size = 0;
		byte[] bytes = null;
		RandomAccessFile rFile = null;
		try {
			rFile = new RandomAccessFile(srcFile, "r");
			// 对文件进行读取操作
			try {
				size = rFile.length();
				bytes = new byte[(int) size];
			} catch (IOException e) {

				e.printStackTrace();
			}
			try {
				rFile.readFully(bytes);
			} catch (IOException e) {

				e.printStackTrace();
			}

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		// 进行文件内容的粘贴
		if(!newFile.exists())//如果文件并不存在,进行重新创建文件
		{
			 try {
				newFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		}
		try {
			RandomAccessFile wFile = new RandomAccessFile(newFile, "rw");
			try {
				wFile.write(bytes);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
                   System.out.println("文件:" + srcFile.getName() + "已经成功写入到文件:" 
                   + newFile.getName()+"中去");
		}

	}

	public static void main(String[] args) {
		// 进行方法的调用
		copyAndStick();
	}

}

猜你喜欢

转载自blog.csdn.net/qq_44213634/article/details/98603000