java中复制文件和文件夹Demo,压缩单个文件夹Demo,压缩文件和文件夹Demo

public void compressFoldersAndFiles(List<String> filesAndFoldersList, String tempfolder, String filename)
			throws Exception {
		Calendar rightNow = Calendar.getInstance();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd_hhmmss");
		String folder = "C:\\" + fmt.format(rightNow.getTime()); // 临时存储文件夹
		if (!filesAndFoldersList.isEmpty()) {
			for (int i = 0; i < filesAndFoldersList.size(); i++) {
				File file = new File(filesAndFoldersList.get(i));
				if (file.isDirectory()) {
					String temp = folder + filesAndFoldersList.get(i).substring(2); // 去掉c盘盘符,保留下载路径
					if (!copyFolder(filesAndFoldersList.get(i), temp)) {
						throw new Exception("filesAndFoldersList copyFolder error");
					}
				} else if (file.isFile()) {
					String temp = folder + filesAndFoldersList.get(i).substring(2); // 去掉c盘盘符
					int b = temp.lastIndexOf("\\");
					String tempFolder = temp.substring(0, b);
					File Tempfile = new File(tempFolder);
					Tempfile.mkdirs();
					if (!copyFile(filesAndFoldersList.get(i), temp)) {
						throw new Exception("filesAndFoldersList copyFile error");
					}
				} else {
					throw new Exception("filesAndFoldersList error");
				}
			}
			compressSingleFolder(folder, tempfolder, filename);
			File file = new File(folder);
			while (file.exists()) { // 删除临时文件夹
				System.gc();
				deleteDir(file);
			}
		} else {
			throw new Exception("filesAndFoldersList is empty");
		}
	}



private static boolean copyFile(String oldPathAndFileName, String targetPathAndFileName) {
		boolean flag = false;
		try {
			int byteread = 0;
			File oldfile = new File(oldPathAndFileName);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(oldPathAndFileName);
				FileOutputStream fs = new FileOutputStream(targetPathAndFileName);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
				flag = true;
				return flag;
			} else {
				flag = false;
				return flag;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	private static boolean copyFolder(String oldPath, String newPath) {
		boolean flag = false;
		try {
			File newFile = new File(newPath);
			newFile.setExecutable(false);
			newFile.setReadable(true, true);
			newFile.setWritable(true, true);
			newFile.mkdirs();
			File a = new File(oldPath);
			if (a.exists()) {
				a.setExecutable(false);
				a.setReadable(true, true);
				a.setWritable(true, true);
				String[] file = a.list();
				File temp = null;
				for (int i = 0; i < file.length; i++) {
					if (oldPath.endsWith(File.separator)) {
						temp = new File(oldPath + file[i]);
					} else {
						temp = new File(oldPath + File.separator + file[i]);
					}
					if (temp.isFile()) {
						FileInputStream input = new FileInputStream(temp);
						FileOutputStream output = new FileOutputStream(
								newPath + File.separator + (temp.getName()).toString());
						byte[] b = new byte[1024 * 5];
						int len;
						while ((len = input.read(b)) != -1) {
							output.write(b, 0, len);
						}
						output.flush();
						output.close();
						input.close();
					}
					if (temp.isDirectory()) {
						copyFolder(oldPath + File.separator + file[i], newPath + File.separator + file[i]);
					}
				}
				flag = true;
				return flag;
			} else {
				flag = false;
				return flag;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
private static List<String> listFile = new ArrayList<String>();

	public void compressSingleFolder(String oldPathAndFolderName, String tempfolder, String filename) throws Exception {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		if (getFile(oldPathAndFolderName)) {
			try {
				File zipFile = new File(tempfolder + "\\" + filename + ".zip");
				if (zipFile.exists()) {
					throw new Exception(tempfolder + " has already exists " + filename + ".zip");
				} else {
					if (!zipFile.exists()) {
						zipFile.getParentFile().mkdirs();
					}
					fos = new FileOutputStream(zipFile);
					zos = new ZipOutputStream(new BufferedOutputStream(fos));
					byte[] bufs = new byte[1024 * 1024];
					for (int i = 0; i < listFile.size(); i++) {
						try {
							ZipEntry zipEntry = new ZipEntry(listFile.get(i));
							zos.putNextEntry(zipEntry);
							fis = new FileInputStream(listFile.get(i));
							bis = new BufferedInputStream(fis, 1024 * 1024);
							int read = 0;
							while ((read = bis.read(bufs, 0, 1024 * 1024)) != -1) {
								zos.write(bufs, 0, read);
							}
						} catch (Exception e) {
							throw new Exception("downloadSingleFolder ZipEntry error");
						}
					}
					listFile.clear();
				}
			} catch (FileNotFoundException | JSONException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				try {
					if (null != bis)
						bis.close();
					if (null != zos)
						zos.close();
					if (null != fos)
						fos.close();
					if (null != fis)
						fis.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		} else {
			throw new Exception("folder not exists or folder is blank");
		}
	}

	private static boolean getFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			File[] tempList = file.listFiles();
			for (File f : tempList) {
				if (f.isFile()) {
					listFile.add(f.getPath());
					continue;
				}
				if (f.isDirectory()) {
					getFile(f.getPath());
				}
			}
			return true;
		} else {
			return false;
		}
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
程序测试可用,直接解压导入到工程就可以,bat文件跟shell文件是用于在window跟linux上直接执行的脚本 我把开发的配置文档附上: 1.程序为定时任务,任务执行时间在bin目录下的配置文件mergeFilleUtil.properties配置,在配置文件,TASK_PERIOD表示任务执行时间间隔,单位为妙,如一天的时间间隔配置是86400,TASK_BEGIN_HOUR表示任务开始的小时时间,比如9点,TASK_BEGIN_MINUTE表任务开始的分钟,比如30分。 2. 程序用log4j记录日志,日志分正常信息跟错误信息两个级别,日志文件存放在log4j文件夹下。考虑到文件很多,日志解压、移动文件每解压、移动1000个记录一次,合并、删除文件每合并、删除50000个记录一次, 3. 启动任务前需配置文件解压合并的路径,本程序需配置的路径如下: 1). PROVINCE_DIR:原始文件存放的路径,必须配置到省的上一级路径,比如存放安徽省的文件路径为E:\test\rootfile\anhui,那么文件的路径必须配置为E:\test\rootfile,否则不能正确显示合并结果; 2). UN_ZIP_PATH:存放解压后的文件的路径; 3). OUT_PATH:存放合并后的文件路径; 4). DONE_FILE_PATH:存放已经解压处理过的文件; 5). DELETE_PATH:配置程序运行结束后欲删除文件的路径,如想删除多个文件夹下的文件,路径之间用逗号隔开,勿加空格,比如:E:\test\rootfile,E:\test\unZip; 4. 注意事项: 本解压合并程序处理文件的逻辑如下: 程序每次解压都去PROVINCE_DIR文件下去解压,将解压后的文件存放到UN_ZIP_PATH下,之后程序启动合并程序合并UN_ZIP_PATH下文件,将合并后的文件按照省份名称存放到OUT_PATH,一个省一个文件。当解压合并结束后,程序将PROVINCE_DIR路径下的文件移动到DONE_FILE_PATH下,并且删除PROVINCE_DIR跟UN_ZIP_PATH下文件,这样保证程序每次运行PROVINCE_DIR文件夹下的文件跟UN_ZIP_PATH下的文件都是最新未处理过的,避免了不断判断文件历史记录所带来的大量时间消耗。 所以为了保证文件解压跟合并的正确性,必须配置好DELETE_PATH路径下的文件,否则合并后的结果是不准确的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值