Java IO 流-- 文件拷贝

IO流操作套路:
1、创建源;
2、选择流;
3、操作;
4、释放资源
上代码:

package com.xzlf.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * 文件拷贝
 * @author xzlf
 *
 */
public class CopyFile {
	public static void main(String[] args) {
//		copy("src/com/xzlf/io/CopyFile.java", "src/CopyFile.txt");
		copy("f:/aa/1.jpg", "src/1.jpg");

	}

	public static void copy(String srcPath, String destPath) {
		// 1、创建源
		File src = new File(srcPath);
		File dest = new File(destPath);
		// 2、选择流
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(src);
			os = new FileOutputStream(dest);
			byte[] flush = new byte[1024];
			int len = -1;
			// 3、操作(循环读取)
			while ((len = is.read(flush)) != -1) {
				os.write(flush, 0, len);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 4、释放资源
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

以上是IO的基本操作,IO的操作都可以按这样的套路来。

posted @ 2020-03-27 02:15  行者老夫  阅读(227)  评论(0编辑  收藏  举报