java简单实现本地拷贝文件与拷贝文件夹

2021/4/28 22:26:53

本文主要是介绍java简单实现本地拷贝文件与拷贝文件夹,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

初步学习,只是简单的写了一下,如有不足之处请大家提出,谢谢。

package util;

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

/**
 * @ClassName: FileUtil
 * @Description: 文件工具类
 * @author yxy
 * @date 2021年4月7日
 */
public class FileUtil {
	private static FileUtil copyFile;

	private FileUtil() {
		// TODO Auto-generated constructor stub
	}

	public static FileUtil getCopyFile() {
		if (copyFile == null) {
			synchronized (FileUtil.class) {
				if (copyFile == null) {
					copyFile = new FileUtil();
				}
			}
		}
		return copyFile;
	}

	/**
	 * @Title: copyFile
	 * @Description: 拷贝文件
	 * @param path 原文件路径
	 * @param newPath 保存路径
	 * @return
	 */
	public boolean copyFile(String path, String newPath) {
		File inputFile = new File(path);
		File outPutFile = new File(newPath);
		BufferedInputStream bi = null;
		BufferedOutputStream bo = null;
		try {
			FileInputStream fi = new FileInputStream(inputFile);
			FileOutputStream fo = new FileOutputStream(outPutFile);
			bi = new BufferedInputStream(fi);
			bo = new BufferedOutputStream(fo);
			byte data[] = new byte[100];
			while (true) {
				int rs = bi.read(data);
				if (rs < 0) {
					break;
				}
				bo.write(data, 0, rs);
			}
			bo.flush();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (bo != null) {
				try {
					bo.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bi != null) {
				try {
					bi.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return false;
	}

	/**
	 * @Title: copyDirectory
	 * @Description: 拷贝文件夹
	 * @param Path 原文件夹路径
	 * @param newPath 保存路径
	 * @return
	 */
	public boolean copyDirectory(String path, String newPath) {
		File nowDir = new File(path);
		new File(newPath + "\\" + nowDir.getName()).mkdir();
		File newDir = new File(newPath + "\\" + nowDir.getName());
		File[] copyFiles = nowDir.listFiles();
		for (File f : copyFiles) {
			if (f.isDirectory()) {
				copyDirectory(f.getAbsolutePath(), newDir.getAbsolutePath());
			}
			if (f.isFile()) {
				copyFile(f.getAbsolutePath(), newDir.getAbsolutePath() + "\\" + f.getName());
			}
		}
		return true;
	}
}



这篇关于java简单实现本地拷贝文件与拷贝文件夹的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程