多线程文件复制工具--复制图片

public static void main(String[] args) throws Exception {
		File file = new File("C:\\Users\\Administrator\\Pictures\\girl.jpg");
		File destFile = new File("d:\\girl.jpg");
		System.out.println(file.length());
		int data1 = (int) (file.length()/2);
		int data2 = (int) (file.length() -data1);
		//存储图片的字节数组输出流
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		Thread t1 = new Thread() {
			public void run() {
				FileImageInputStream input = null;
				try {
					input = new FileImageInputStream(file);
					byte[] buf = new byte[data1];
					input.read(buf);//读到缓冲
					bos.write(buf);//把缓冲写到字节数组输出流
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					try {
						bos.close();
						input.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
		t1.start();
		Thread.sleep(200);//保证先读取第一部分数据,否则可能第二个线程先启动,图片打不开
		Thread t2 = new Thread() {
			public void run() {
				FileImageInputStream input = null;
				try {
					input = new FileImageInputStream(file);
					byte[] buf = new byte[data2];
					input.skipBytes(data1);//跳过读取的
					input.read(buf);//读到缓冲
					bos.write(buf);//把缓冲写到字节数组输出流					
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					try {
						bos.close();
						input.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
		t2.start();
		t1.join();
		t2.join();
		//图片数据都在ByteArrayOutputStream		
		FileImageOutputStream output = new FileImageOutputStream(destFile);
		System.out.println("==="+bos.toByteArray().length);
		output.write(bos.toByteArray());
		output.close();
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Linux shell 的 `rsync` 命令来实现多线程复制文件的脚本。`rsync` 是一个功能强大的文件复制工具,支持多线程复制和增量复制。 以下是一个简单的示例脚本,可以在 Linux shell 中运行: ```shell #!/bin/bash # 源文件目录 source_dir="/path/to/source" # 目标文件目录 target_dir="/path/to/target" # 并发线程数 threads=4 # 复制文件 rsync -r --progress --human-readable --stats --partial --info=progress2 --inplace --files-from=<(cd $source_dir && find . -type f) $source_dir $target_dir --parallel=$threads ``` 在脚本中,你需要修改 `source_dir` 和 `target_dir` 变量为你实际的源文件目录和目标文件目录。同时,你可以根据需要调整并发线程数 `threads`。 脚本中使用了 `rsync` 命令的多个参数,具体含义如下: - `-r`:递归复制文件夹及其内容。 - `--progress`:显示复制进度。 - `--human-readable`:以人类可读的方式显示进度。 - `--stats`:显示复制统计信息。 - `--partial`:支持断点续传。 - `--info=progress2`:显示更详细的进度信息。 - `--inplace`:直接在目标位置进行修改,而不是创建临时文件。 - `--files-from=<(cd $source_dir && find . -type f)`:从源文件目录中的文件列表中复制文件。 - `$source_dir` 和 `$target_dir`:源文件目录和目标文件目录。 - `--parallel=$threads`:指定并发线程数。 请注意,`rsync` 命令在复制过程中会自动检测已复制文件,只复制有变化的部分,以实现增量复制。 希望这个示例能帮助到你!如果有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值