用 FileChannel 拷贝文件

本文介绍了一种使用文件通道和流来高效复制文件的方法,并提供了代码实现,对比了两种技术的性能差异。

原文链接:http://www.2cto.com/kf/201108/102100.html

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

/**
 * Copy files, using two techniques, FileChannels and streams. Using
 * FileChannels is usually faster than using streams.
 */
public final class CopyFiles {

	/* Change these settings before running this class. */

	/** The file to be copied. */
	public static final String INPUT_FILE = "C:\\TEMP\\cottage.jpg";

	/**
	 * The name of the copy to be created by this class. If this file doesn't
	 * exist, it will be created, along with any needed parent directories.
	 */
	public static final String COPY_FILE_TO = "C:\\TEMP10\\cottage_2.jpg";

	/** Run the example. */
	public static void main(String... aArgs) throws IOException {
		File source = new File(INPUT_FILE);
		File target = new File(COPY_FILE_TO);
		CopyFiles test = new CopyFiles();
		test.copyWithChannels(source, target, false);
		// test.copyWithStreams(source, target, false);
		log("Done.");
	}

	/** This may fail for VERY large files. */
	private void copyWithChannels(File aSourceFile, File aTargetFile,
			boolean aAppend) {
		log("Copying files with channels.");
		ensureTargetDirectoryExists(aTargetFile.getParentFile());
		FileChannel inChannel = null;
		FileChannel outChannel = null;
		FileInputStream inStream = null;
		FileOutputStream outStream = null;
		try {
			try {
				inStream = new FileInputStream(aSourceFile);
				inChannel = inStream.getChannel();
				outStream = new FileOutputStream(aTargetFile, aAppend);
				outChannel = outStream.getChannel();
				long bytesTransferred = 0;
				// defensive loop - there's usually only a single iteration :
				while (bytesTransferred < inChannel.size()) {
					bytesTransferred += inChannel.transferTo(0,
							inChannel.size(), outChannel);
				}
			} finally {
				// being defensive about closing all channels and streams
				if (inChannel != null)
					inChannel.close();
				if (outChannel != null)
					outChannel.close();
				if (inStream != null)
					inStream.close();
				if (outStream != null)
					outStream.close();
			}
		} catch (FileNotFoundException ex) {
			log("File not found: " + ex);
		} catch (IOException ex) {
			log(ex);
		}
	}

	public void copyWithStreams(File aSourceFile, File aTargetFile,
			boolean aAppend) {
		log("Copying files with streams.");
		ensureTargetDirectoryExists(aTargetFile.getParentFile());
		InputStream inStream = null;
		OutputStream outStream = null;
		try {
			try {
				byte[] bucket = new byte[32 * 1024];
				inStream = new BufferedInputStream(new FileInputStream(aSourceFile));
				outStream = new BufferedOutputStream(new FileOutputStream(aTargetFile, aAppend));
				int bytesRead = 0;
				while (bytesRead != -1) {
					bytesRead = inStream.read(bucket); // -1, 0, or more
					if (bytesRead > 0) {
						outStream.write(bucket, 0, bytesRead);
					}
				}
			} finally {
				if (inStream != null)
					inStream.close();
				if (outStream != null)
					outStream.close();
			}
		} catch (FileNotFoundException ex) {
			log("File not found: " + ex);
		} catch (IOException ex) {
			log(ex);
		}
	}

	private void ensureTargetDirectoryExists(File aTargetDir) {
		if (!aTargetDir.exists()) {
			aTargetDir.mkdirs();
		}
	}

	private static void log(Object aThing) {
		System.out.println(String.valueOf(aThing));
	}
}


源码来自:https://pan.quark.cn/s/a4b39357ea24 《C++ Primer》作为C++编程领域中的一部权威著作,主要服务于初学者和经验丰富的开发者,致力于帮助他们深入掌握C++的核心知识。 第一章通常会详细讲解C++语言的基础概念和语法结构,包括变量的使用、数据类型的分类、常量的定义、运算符的应用以及基础的输入输出操作。 接下来,我们将对这一章中的核心知识点和可能的习题解答进行深入分析。 ### 1. 变量与数据类型在C++编程中,变量被视为存储数据的媒介。 每一个变量都必须预先声明其数据类型,常见的数据类型有整型(int)、浮点型(float)、双精度浮点型(double)以及字符型(char)。 例如:```cppint age = 25; // 声明一个整型变量age并赋予其初始值25float weight = 70.5f; // 声明一个浮点型变量weight并赋予其初始值70.5char grade = A; // 声明一个字符型变量grade并赋予其初始值A```### 2. 常量与字面量常量指的是不可更改的值,可以通过`const`关键字进行声明。 例如:```cppconst int MAX_SIZE = 100; // 声明一个整型常量MAX_SIZE,其值为100```字面量是指程序中直接书写的值,如`42`、`3.14`或`"Hello"`。 ### 3. 运算符C++提供了多种运算符,涵盖了算术运算符(+,-,*,/,%)、比较运算符(==,!=,<,>,<=,>=)、逻辑运算符(&&,||,!)以及赋值运算符(=,+=,-=,*=,/=,%=)等。 ### 4. 输入与输出在C++中,使用`std::cin`来实现输...
内容概要:本文详细介绍了一个基于C++的仓库存储管理系统的设计与实现,涵盖了项目背景、目标、挑战及解决方案,并系统阐述了整体架构设计、数据库建模、功能模块划分、权限安全、并发控制、数据一致性保障、异常处理与可扩展性等关键内容。通过面向对象编程思想,采用分层架构与模块化解耦设计,结合STL容器、多线程、锁机制等C++核心技术,实现了高效的库存管理功能,包括入库、出库、盘点、调拨、权限控制、日志追踪与智能报表分析。文中还提供了核心类如Inventory(库存)、User(用户权限)、LogEntry(操作日志)及WarehouseManager(主控制器)的代码示例,展示了数据结构设计与关键算法逻辑。; 适合人群:具备C++编程基础,熟悉面向对象设计与基本数据结构的软件开发人员,尤其适合从事企业级管理系统开发或希望深入理解系统架构设计的中级开发者(工作1-3年);也适用于计算机相关专业学生进行课程设计或毕业项目参考; 使用场景及目标:①学习如何使用C++构建复杂业务系统的整体架构与模块划分方法;②掌握高并发、数据一致性、权限控制、异常处理等企业级系统关键技术的实现思路;③理解仓储管理业务流程及其在软件系统中的建模与落地方式;④为开发类似ERP、MES等后台管理系统提供技术原型与设计参考; 阅读建议:此资源不仅提供理论架构与代码片段,更强调系统设计的完整性与工程实践性。建议读者结合代码示例动手实现核心模块,深入理解类之间的关系与交互逻辑,重点关注多线程安全、事务管理与权限校验等难点环节,并尝试扩展功能如对接GUI界面或数据库持久化模块,以全面提升系统开发能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值