java实现文件或图片拷贝

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageAndFileCopy {

	public static final String OLDPATH = "C://head2.jpg";
	public static final String NEWPATH = "d://111.jpg";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 稍微简洁的处理方法
//		  try { // System.out.println(request.getContextPath());
//			FileInputStream imageInput = new FileInputStream("C://head2.jpg");
//			FileOutputStream imageOutput = new FileOutputStream("d://111.jpg");
//			byte[] buf = new byte[imageInput.available()];
//			imageInput.read(buf);
//			imageOutput.write(buf);
//			imageInput.close();
//			imageOutput.close();
//			System.out.println("file copy success!");
//		} catch (IOException e) {
//			System.out.println("copy file failed!");
//		}
		

		ImageAndFileCopy testMain = new ImageAndFileCopy();

		testMain.imageCopy();

	}

	public void imageCopy() {

		File old = new File(ImageAndFileCopy.OLDPATH);
		File newImage = new File(ImageAndFileCopy.NEWPATH);
		// newImage.mkdirs();
		FileInputStream imageInput = null;
		FileOutputStream imageOutput = null;

		try {
			if (!old.exists()) {
				System.out.println("the file is not exists");
			} else {
				imageInput = new FileInputStream(old);

				if (!newImage.exists()) {
					// newImage.mkdir();
					newImage.createNewFile();

				}
				imageOutput = new FileOutputStream(newImage + "/"
						+ old.getName());

				byte[] temp = new byte[1000];
				int size = imageInput.read(temp);
				while (size != -1) {
					imageOutput.write(temp);
					size = imageInput.read(temp);
				}
				System.out.println("the File Copy is success!");
			}
		} catch (FileNotFoundException fileNot) {
			System.out.println("the File Copy is Failed!");
			fileNot.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("the File Copy is Failed!");
		} finally {
			try {
				imageInput.close();
				imageOutput.close();

			} catch (Exception ex) {
			}

		}

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值