java io复制操作

package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class Test {
	public static void main(String[] args) throws IOException {
		// 图片,文件都可以复制
		copyFile("C:/Users/Administrator/Desktop/1.jpg", "D:/1.jpg");
	}

    /**
    * oldPath代表要复制的资源路径, newPath代表要复制到哪个位置
    */
	public static void copyFile(String oldPath, String newPath) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos =null;
		try {
			 fis = new FileInputStream(new File(oldPath));
			 fos = new FileOutputStream(new File(newPath));
			
			 bis = new BufferedInputStream(fis);
			 bos = new BufferedOutputStream(fos);
			
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			bos.flush();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != bos) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != bis) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/sinat_37795871/article/details/84785278