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

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();
	}
发布了91 篇原创文章 · 获赞 43 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/kongfanyu/article/details/103786966