Java tutorial
/* * Copyright (c) 2016 yunmle.com(?). * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.yunmel.syncretic.utils.io; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.System.err; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.Enumeration; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.io.Files; /** * * @description I/O? * * @author xuyq - chainisit@126.com * @since 1.0 - 2016715 */ public class IOUtils extends FileUtils { // create md5 for file protected static MessageDigest messagedigest = null; protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; static { try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } private static Logger log = LoggerFactory.getLogger(IOUtils.class); /** * ??? * * @param srcFileName ??? * @param descFileName ?? * @return ??true?false */ public static boolean copyFile(String srcFileName, String descFileName) { return IOUtils.copyFileCover(srcFileName, descFileName, false); } /** * ? * * @param fileName * @return */ public static String getFileSuffix(String fileName) { if (fileName != null && fileName.indexOf(".") != -1) { return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); } return null; } /** * ?????? */ public static String getFileNameNoSuffix(String fileName) { if (fileName != null && fileName.indexOf(".") != -1) { return fileName.substring(0, fileName.lastIndexOf(".")); } return fileName; } /** * ?? * * @param srcFileName ??? * @param descFileName ?? * @param coverlay ? * @return ??true?false */ public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); // ?? if (!srcFile.exists()) { log.debug("?? " + srcFileName + " ?!"); return false; } // ??? else if (!srcFile.isFile()) { log.debug("?" + srcFileName + " ?!"); return false; } File descFile = new File(descFileName); // ? if (descFile.exists()) { // ? if (coverlay) { log.debug("!"); if (!IOUtils.delFile(descFileName)) { log.debug(" " + descFileName + " !"); return false; } } else { log.debug("? " + descFileName + " !"); return false; } } else { if (!descFile.getParentFile().exists()) { // ? log.debug("?!"); // if (!descFile.getParentFile().mkdirs()) { log.debug("!"); return false; } } } // ? // ?? int readByte = 0; InputStream ins = null; OutputStream outs = null; try { // ? ins = new FileInputStream(srcFile); // ? outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; // ?1024readByte-1?? while ((readByte = ins.read(buf)) != -1) { // ??? outs.write(buf, 0, readByte); } log.debug("?? " + srcFileName + " " + descFileName + "?!"); return true; } catch (Exception e) { log.debug("?" + e.getMessage()); return false; } finally { // ????? if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } /** * ?? * * @param srcDirName ??? * @param descDirName ?? * @return ??true?false */ public static boolean copyDirectory(String srcDirName, String descDirName) { return IOUtils.copyDirectoryCover(srcDirName, descDirName, false); } /** * ? * * @param srcDirName ??? * @param descDirName ?? * @param coverlay ? * @return ??true?false */ public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) { File srcDir = new File(srcDirName); // ?? if (!srcDir.exists()) { log.debug("?? " + srcDirName + " ?!"); return false; } // ?? else if (!srcDir.isDirectory()) { log.debug("?" + srcDirName + " ?!"); return false; } // ??? String descDirNames = descDirName; if (!descDirNames.endsWith(File.separator)) { descDirNames = descDirNames + File.separator; } File descDir = new File(descDirNames); // if (descDir.exists()) { if (coverlay) { // ? log.debug("!"); if (!IOUtils.delFile(descDirNames)) { log.debug(" " + descDirNames + " !"); return false; } } else { log.debug("? " + descDirNames + " !"); return false; } } else { // log.debug("?!"); if (!descDir.mkdirs()) { log.debug("!"); return false; } } boolean flag = true; // ?????? File[] files = srcDir.listFiles(); for (int i = 0; i < files.length; i++) { // ?? if (files[i].isFile()) { flag = IOUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName()); // ? if (!flag) { break; } } // ?? if (files[i].isDirectory()) { flag = IOUtils.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName()); // ? if (!flag) { break; } } } if (!flag) { log.debug("? " + srcDirName + " " + descDirName + " !"); return false; } log.debug("? " + srcDirName + " " + descDirName + " ?!"); return true; } /** * * ?? * * @param fileName ?? * @return ?true?false */ public static boolean delFile(String fileName) { File file = new File(fileName); if (!file.exists()) { log.debug(fileName + " ?!"); return true; } else { if (file.isFile()) { return IOUtils.deleteFile(fileName); } else { return IOUtils.deleteDirectory(fileName); } } } /** * * ? * * @param fileName ?? * @return ?true?false */ public static boolean deleteFile(String fileName) { File file = new File(fileName); if (file.exists() && file.isFile()) { if (file.delete()) { log.debug("? " + fileName + " ?!"); return true; } else { log.debug("? " + fileName + " !"); return false; } } else { log.debug(fileName + " ?!"); return true; } } /** * * ? * * @param dirName * @return ?true?false */ public static boolean deleteDirectory(String dirName) { String dirNames = dirName; if (!dirNames.endsWith(File.separator)) { dirNames = dirNames + File.separator; } File dirFile = new File(dirNames); if (!dirFile.exists() || !dirFile.isDirectory()) { log.debug(dirNames + " ?!"); return true; } boolean flag = true; // ?? File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { // ? if (files[i].isFile()) { flag = IOUtils.deleteFile(files[i].getAbsolutePath()); // if (!flag) { break; } } // ? else if (files[i].isDirectory()) { flag = IOUtils.deleteDirectory(files[i].getAbsolutePath()); // ? if (!flag) { break; } } } if (!flag) { log.debug("!"); return false; } // ? if (dirFile.delete()) { log.debug(" " + dirName + " ?!"); return true; } else { log.debug(" " + dirName + " !"); return false; } } /** * ? * * @param descFileName ??? * @return ?true?false */ public static boolean createFile(String descFileName) { File file = new File(descFileName); if (file.exists()) { log.debug(" " + descFileName + " !"); return false; } if (descFileName.endsWith(File.separator)) { log.debug(descFileName + " ?!"); return false; } if (!file.getParentFile().exists()) { // ? if (!file.getParentFile().mkdirs()) { log.debug("!"); return false; } } // try { if (file.createNewFile()) { log.debug(descFileName + " ?!"); return true; } else { log.debug(descFileName + " !"); return false; } } catch (Exception e) { e.printStackTrace(); log.debug(descFileName + " !"); return false; } } /** * * * @param descDirName ??,? * @return ?true?false */ public static boolean createDirectory(String descDirName) { String descDirNames = descDirName; if (!descDirNames.endsWith(File.separator)) { descDirNames = descDirNames + File.separator; } File descDir = new File(descDirNames); if (descDir.exists()) { log.debug(" " + descDirNames + " !"); return false; } // if (descDir.mkdirs()) { log.debug(" " + descDirNames + " ?!"); return true; } else { log.debug(" " + descDirNames + " !"); return false; } } /** * ? * * @param files * @param out ? * @throws IOException * @throws Exception */ public static void zipDownLoad(Map<File, String> downQuene, HttpServletResponse response) throws IOException { ServletOutputStream out = response.getOutputStream(); ZipOutputStream zipout = new ZipOutputStream(out); ZipEntry entry = null; zipout.setLevel(1); // zipout.setEncoding("GBK"); if (downQuene != null && downQuene.size() > 0) { for (Entry<File, String> fileInfo : downQuene.entrySet()) { File file = fileInfo.getKey(); try { String filename = new String(fileInfo.getValue().getBytes(), "GBK"); entry = new ZipEntry(filename); entry.setSize(file.length()); zipout.putNextEntry(entry); } catch (IOException e) { // Logger.getLogger(FileUtil.class).warn(":", e); } BufferedInputStream fr = new BufferedInputStream(new FileInputStream(fileInfo.getKey())); int len; byte[] buffer = new byte[1024]; while ((len = fr.read(buffer)) != -1) zipout.write(buffer, 0, len); fr.close(); } } zipout.finish(); zipout.flush(); // out.flush(); } /** * * * @param srcDirName * @param fileName ????*"" * @param descFileName zip */ public static void zipFiles(String srcDirName, String fileName, String descFileName) { // ? if (srcDirName == null) { log.debug(" " + srcDirName + " ?!"); return; } File fileDir = new File(srcDirName); if (!fileDir.exists() || !fileDir.isDirectory()) { log.debug(" " + srcDirName + " ?!"); return; } String dirPath = fileDir.getAbsolutePath(); File descFile = new File(descFileName); try { ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile)); if ("*".equals(fileName) || "".equals(fileName)) { IOUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts); } else { File file = new File(fileDir, fileName); if (file.isFile()) { IOUtils.zipFilesToZipFile(dirPath, file, zouts); } else { IOUtils.zipDirectoryToZipFile(dirPath, file, zouts); } } zouts.close(); log.debug(descFileName + " ?!"); } catch (Exception e) { log.debug("" + e.getMessage()); e.printStackTrace(); } } /** * ZIPZIPdescFileName * * @param zipFileName ?ZIP * @param descFileName */ public static boolean unZipFiles(String zipFileName, String descFileName) { String descFileNames = descFileName; if (!descFileNames.endsWith(File.separator)) { descFileNames = descFileNames + File.separator; } try { // ?ZIPZipFile ZipFile zipFile = new ZipFile(zipFileName); ZipEntry entry = null; String entryName = null; String descFileDir = null; byte[] buf = new byte[4096]; int readByte = 0; // ?ZIPentry @SuppressWarnings("rawtypes") Enumeration enums = zipFile.entries(); // ??entry while (enums.hasMoreElements()) { entry = (ZipEntry) enums.nextElement(); // entry?? entryName = entry.getName(); descFileDir = descFileNames + entryName; if (entry.isDirectory()) { // entry new File(descFileDir).mkdirs(); continue; } else { // entry new File(descFileDir).getParentFile().mkdirs(); } File file = new File(descFileDir); // ? OutputStream os = new FileOutputStream(file); // ZipFileentry? InputStream is = zipFile.getInputStream(entry); while ((readByte = is.read(buf)) != -1) { os.write(buf, 0, readByte); } os.close(); is.close(); } zipFile.close(); log.debug("?!"); return true; } catch (Exception e) { log.debug("" + e.getMessage()); return false; } } /** * ZIP? * * @param dirPath * @param fileDir ? * @param zouts ? */ public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) { if (fileDir.isDirectory()) { File[] files = fileDir.listFiles(); // if (files.length == 0) { // ? ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir)); try { zouts.putNextEntry(entry); zouts.closeEntry(); } catch (Exception e) { e.printStackTrace(); } return; } for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { // IOUtils.zipFilesToZipFile(dirPath, files[i], zouts); } else { // IOUtils.zipDirectoryToZipFile(dirPath, files[i], zouts); } } } } /** * ZIP? * * @param dirPath * @param file * @param zouts ? */ public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) { FileInputStream fin = null; ZipEntry entry = null; // ? byte[] buf = new byte[4096]; int readByte = 0; if (file.isFile()) { try { // ? fin = new FileInputStream(file); // ZipEntry entry = new ZipEntry(getEntryName(dirPath, file)); // ? zouts.putNextEntry(entry); // ? while ((readByte = fin.read(buf)) != -1) { zouts.write(buf, 0, readByte); } zouts.closeEntry(); fin.close(); System.out.println(" " + file.getAbsolutePath() + " zip!"); } catch (Exception e) { e.printStackTrace(); } } } /** * ?ZIPentry????? * * @param dirPath ?? * @param file entry?? * @return */ private static String getEntryName(String dirPath, File file) { String dirPaths = dirPath; if (!dirPaths.endsWith(File.separator)) { dirPaths = dirPaths + File.separator; } String filePath = file.getAbsolutePath(); // entry????"/" if (file.isDirectory()) { filePath += "/"; } int index = filePath.indexOf(dirPaths); return filePath.substring(index + dirPaths.length()); } // public static String getAbsolutePath(String urlPath) { // if (StringUtils.isBlank(urlPath)) { // return ""; // } else { // return SpringContextHolder.getRootRealPath() + urlPath.substring(urlPath.indexOf("/", 1), // urlPath.length()); // } // } /** * * * @param content * @param filePath */ public static void writeFile(String content, String filePath) { try { if (IOUtils.createFile(filePath)) { FileWriter fileWriter = new FileWriter(filePath, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(content); bufferedWriter.close(); fileWriter.close(); } else { log.info("??"); } } catch (Exception e) { e.printStackTrace(); } } public static void downloadFile(HttpServletResponse response, String filePath, String fileName, boolean inline) throws Exception { File file = new File(filePath); downloadFile(response, file, fileName, inline); } public static void downloadFile(HttpServletResponse response, String filePath, String fileName) throws Exception { File file = new File(filePath); downloadFile(response, file, fileName, false); } public static void downloadFile(HttpServletResponse response, File file, String fileName) throws Exception { downloadFile(response, file, fileName, false); } /** * * * @param filePath * @param fileName ?? * @param inline ?? * @throws Exception */ public static void downloadFile(HttpServletResponse response, File file, String fileName, boolean inline) throws Exception { OutputStream outp = null; FileInputStream br = null; int len = 0; try { br = new FileInputStream(file); response.reset(); outp = response.getOutputStream(); outp.flush(); response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); String header = (inline ? "inline" : "attachment") + ";filename=" + new String(fileName.getBytes(), "ISO8859-1"); response.addHeader("Content-Disposition", header); byte[] buf = new byte[1024]; while ((len = br.read(buf)) != -1) { outp.write(buf, 0, len); } outp.flush(); outp.close(); } finally { if (br != null) { if (0 == br.available()) { br.close(); } } } } /** * (??) * * @param response * @param is ? * @param realName ?? */ public static void downloadFile(HttpServletResponse response, InputStream is, String realName) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { response.setContentType("text/html;charset=UTF-8"); // request.setCharacterEncoding("UTF-8"); long fileLength = is.available(); response.setContentType("application/octet-stream"); realName = new String(realName.getBytes("GBK"), "ISO8859-1"); response.setHeader("Content-disposition", "attachment; filename=" + realName); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(is); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { // e.printStackTrace();//??? } finally { try { bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * * * @param saveDirectory ? * @param fileName ??? * @throws Exception */ // public static List<UploadFile> multipleUploadFile(String saveDirectory, String fileName, // HttpServletRequest request) // throws Exception { // List<UploadFile> files = Lists.newArrayList(); // MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // // Map<String, MultipartFile> fMap = multipartRequest.getFileMap(); // Iterator<String> it = fMap.keySet().iterator(); // while (it.hasNext()) { // String parameterName = it.next(); // MultipartFile originalFile = fMap.get(parameterName); // String originalFilename = originalFile.getOriginalFilename(); // File dirPath = new File(saveDirectory); // if (!dirPath.exists()) { // dirPath.mkdirs(); // } // originalFile.transferTo(dirPath); // // UploadFile file = new UploadFile(parameterName, saveDirectory, fileName, originalFilename, // originalFile.getContentType()); // files.add(file); // } // // return files; // } /** * ? * * @param saveDirectory ? * @param fileName ??? * @throws Exception */ // public static UploadFile singleUploadFile(String saveDirectory, String fileName, // HttpServletRequest request) // throws Exception { // List<UploadFile> files = multipleUploadFile(saveDirectory, fileName, request); // return CollectionUtils.isEmpty(files) ? null : files.get(0); // } /** * ?MD5 * * @param file * @return * @throws IOException * @date 2012-1-9?3:15:43 */ public static String getFileMD5String(File file) { try { InputStream fis; fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int numRead = 0; while ((numRead = fis.read(buffer)) > 0) { messagedigest.update(buffer, 0, numRead); } fis.close(); return bufferToHex(messagedigest.digest()); } catch (Exception e) { return UUID.randomUUID().toString().replaceAll("-", ""); } } public static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); } private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); } private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// ? 4 ?? // ????,????? char c1 = hexDigits[bt & 0xf];// ? 4 ?? stringbuffer.append(c0); stringbuffer.append(c1); } /** * ???? * * @param fileSize ? * @return */ public static String getHumanSize(long fileSize) { // ? DecimalFormat df = new DecimalFormat("#.##"); String[] units = new String[] { "", "KB", "MB", "GB" }; int i = 0; double size = fileSize; while (size > 1024) { size = size / 1024; i++; } return (df.format(size)) + units[i]; } /** * ? * * @param files * @param out ? * @throws java.io.IOException * @throws Exception */ public static void zipDownLoad(File file, HttpServletResponse response) throws IOException { ServletOutputStream out = response.getOutputStream(); ZipOutputStream zipout = new ZipOutputStream(out); zipout.setLevel(1); // zipout.setEncoding("GBK"); for (File f : file.listFiles()) { if (f.isFile()) { compressFile(f, f.getName(), zipout, ""); } else { compressFolder(f, f.getName(), zipout, ""); } } zipout.finish(); zipout.flush(); } private static void compressFolder(File dir, String fileName, ZipOutputStream zipout, String baseDir) { if (!dir.exists()) { return; } File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { if (baseDir.equals("/")) { baseDir = ""; } compressFolder(files[i], files[i].getName(), zipout, baseDir + fileName + "/"); } else { compressFile(files[i], files[i].getName(), zipout, baseDir + fileName + "/"); } } } private static void compressFile(File file, String fileName, ZipOutputStream zipout, String baseDir) { try { ZipEntry entry = null; if (baseDir.equals("/")) { baseDir = ""; } String filename = new String((baseDir + fileName).getBytes(), "GBK"); entry = new ZipEntry(filename); entry.setSize(file.length()); zipout.putNextEntry(entry); BufferedInputStream fr = new BufferedInputStream(new FileInputStream(file)); int len; byte[] buffer = new byte[1024]; while ((len = fr.read(buffer)) != -1) zipout.write(buffer, 0, len); fr.close(); } catch (IOException e) { } } public static void fileWrite(final String fileName, final String contents) { checkNotNull(fileName, "Provided file name for writing must NOT be null."); checkNotNull(contents, "Unable to write null contents."); final File newFile = new File(fileName); try { Files.write(contents.getBytes("utf-8"), newFile); } catch (IOException fileIoEx) { err.println("ERROR trying to write to file '" + fileName + "' - " + fileIoEx.toString()); } } }