Java 实现复制文本文件的两种方法

本文介绍使用Java中的FileChannel和传统IO方法复制文本文件的具体步骤。通过FileChannel的map方法可以高效地将源文件映射到内存缓冲区,再将缓冲区内容写入目标文件;而传统的读写方式则涉及使用BufferedReader和PrintWriter逐行读取和写入文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java实现复制文本文件的两种方法

FileChannel这个类是继承于抽象类AbstractInterruptibleChannel,实现了接口ByteChannel,GatheringByteChannel,ScatteringByteChannel。

FileChannel这个是最便捷的方法实现复制文件,当然也有一种笨的方法实现复制文件,用读取文件,创建文件,写入文件的方法实现FileChannel这个方法

FileChannel 方法实现复制文本

public class MainCopy {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileChannel in=null;
		FileChannel out=null;
		File f1=new File("channel1.txt");
		File f2=new File("channel2.txt");
		
		try {
			in=new FileInputStream(f1).getChannel();
			ByteBuffer byteBu=in.map(FileChannel.MapMode.READ_ONLY, 0,f1.length());
			out=new FileOutputStream(f2).getChannel();
			out.write(byteBu);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}

用读写文件的方法实现

<pre name="code" class="java">public class MainCopy2 {
	static PrintWriter pw=null;

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//读取文件
		InputStream in=new FileInputStream("channel1.txt");
		InputStreamReader iread=new InputStreamReader(in);
		BufferedReader bf=new BufferedReader(iread);
		//复制文件
		File f2=new File("channel2.txt");
		OutputStream os=new FileOutputStream(f2);
		OutputStreamWriter ow=new OutputStreamWriter(os);
	    pw=new PrintWriter(ow);
		String len=null;
		while((len=bf.readLine())!=null){
			copyfile(len);
		}
		bf.close();
		pw.close();
	}
	//复制两个文件的内容
	static void copyfile(String content) throws FileNotFoundException{
		pw.println(content);
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值