java实现文件的复制,删除,解压
废话不多说,代码如下:
(一)复制文件代码
public static void copyFile(File sourceFile, File targetFile) throws IOException{ BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try { // 新建文件输入流并对它进行缓冲 inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); // 新建文件输出流并对它进行缓冲 outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); // 缓冲数组 byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // 刷新此缓冲的输出流 outBuff.flush(); } finally { // 关闭流 if (inBuff != null) inBuff.close(); if (outBuff != null) outBuff.close(); } }
(二)解压zip格式文件的代码
public static void unzipFile(String source, String target) throws IOException { ZipFile zipFile = new ZipFile(new File(source), "GBK"); System.err.println("文件解压开始"); Enumeration<?> e = zipFile.getEntries(); ZipEntry zipEntry; while (e.hasMoreElements()) { zipEntry = (ZipEntry) e.nextElement(); InputStream fis = zipFile.getInputStream(zipEntry); if (!zipEntry.isDirectory()) { File file = new File(target + File.separator + zipEntry.getName()); File parentFile = file.getParentFile(); parentFile.mkdirs(); FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len; while ((len = fis.read(b, 0, b.length)) != -1) { fos.write(b, 0, len); } fos.close(); fis.close(); } } zipFile.close(); System.err.println("文件解结束"); }
(三)删除文件的代码
public static void delFile(File targetFile){ if (targetFile.exists() && targetFile.isDirectory()) {// 判断是文件还是目录 if (targetFile.listFiles().length == 0) {// 若目录下没有文件则直接删除 targetFile.delete(); } else {// 若有则把文件放进数组,并判断是否有下级目录 File del[] = targetFile.listFiles(); int i = targetFile.listFiles().length; for (int j = 0; j < i; j++) { if (del[j].isDirectory()) { delFile(new File(del[j].getAbsolutePath()));// 递归调用del方法并取得子目录路径 } del[j].delete();// 删除文件 } } } }