`
wnzz95391511
  • 浏览: 124801 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java 实现 copy 文件夹功能

阅读更多
用java实现一个复制文件夹内容到另一个文件夹中的功能
/**
 * A class of dealing file
 * 
 * @author Meng Wang
 * 
 */
public class FileDeal {

	/**
	 * copy all files of a file path to another file path
	 * 
	 * @param fromFilePath
	 * @param toFilePath
	 */
	public void copyFileDir(String fromFilePath, String toFilePath) {
		File fromFileDir = new File(fromFilePath);
		File toFileDir = new File(toFilePath);

		// if new File Path is not exist,create it.
		if (!toFileDir.exists()) {
			toFileDir.mkdirs();
		}
		boolean isToFileSeparetor = isFileSeparetor(fromFilePath);
		boolean isFromFileSeparetor = isFileSeparetor(toFilePath);

		String[] childFileList = fromFileDir.list();

		for (String childFileString : childFileList) {
			File childFile = new File(fromFileDir.getPath() + File.separator
					+ childFileString);
			String fileName = childFile.getName();
			if (!childFile.isDirectory()) {
				try {
					FileInputStream fileInputStream = new FileInputStream(
							childFile);

					File toFile;
					if (isToFileSeparetor) {
						toFile = new File(toFilePath + fileName);
					} else {
						toFile = new File(toFilePath + File.separator
								+ fileName);
					}

					FileOutputStream fileOutputStream = new FileOutputStream(
							toFile);

					byte[] b = new byte[1024];

					try {
						while (fileInputStream.read(b) != -1) {
							fileOutputStream.write(b);
						}
						fileInputStream.close();
						fileOutputStream.flush();
						fileOutputStream.close();
					} catch (IOException e) {

						e.printStackTrace();
					}

				} catch (FileNotFoundException e) {
					System.err.print(e);
				}
			} else {
				String childFromFilePath = null;
				String childToFilePath = null;

				childFromFilePath = isFromFileSeparetor ? fromFilePath
						+ fileName : fromFilePath + File.separator + fileName;
				childToFilePath = isToFileSeparetor ? toFilePath + fileName
						: toFilePath + File.separator + fileName;

				copyFileDir(childFromFilePath, childToFilePath);
			}
		}

	}

	/**
	 * if the filePath is end with fileSeparetor sign
	 * @param toFilePath
	 * @return
	 */
	public boolean isFileSeparetor(String filePath) {
		if (filePath.lastIndexOf(File.separator) == filePath.length() - 1) {
			return true;
		} else {
			return false;
		}
	}

	public static void main(String[] args) {

		FileDeal fileDeal = new FileDeal();

		fileDeal.copyFileDir("E:\\my space", "E:\\wang space");

	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics