Java tutorial
/* * Copyright 2013 The Solmix Project * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.gnu.org/licenses/ * or see the FSF site: http://www.fsf.org. */ package org.solmix.commons.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.text.DecimalFormat; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; /** * ??cmmons FileUtils * @author solmix.f@gmail.com * @version $Id$ 20141114 */ public class Files { /** * ?MD5 * * @param file * @return */ public static String getMd5ByFile(File file) { String value = null; FileInputStream in = null; try { in = new FileInputStream(file); MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(byteBuffer); BigInteger bi = new BigInteger(1, md5.digest()); value = bi.toString(16); } catch (Exception e) { e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return value; } /** * ?? * * @param file * @return */ public static long getFileLength(File file) throws IOException { FileInputStream fis = null; fis = new FileInputStream(file); long size = fis.available(); IOUtils.closeQuietly(fis); return size; } /** * ? * * @param file * @return * @throws IOException */ public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } byte[] bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("??: " + file.getName()); } is.close(); return bytes; } /** * ??30KB15.5MB * * @param file * @return * @throws IOException */ public static String getFileSize(File file) throws IOException { long size = getFileLength(file); DecimalFormat df = new DecimalFormat("###.##"); float f; if (size < 1024 * 1024) { f = (float) size / (float) 1024; return (df.format(new Float(f).doubleValue()) + " KB"); } else { f = (float) size / (float) (1024 * 1024); return (df.format(new Float(f).doubleValue()) + " MB"); } } /** * ? * * @param f1 * ? * @param f2 * * @throws Exception */ public static void copyFile(File f1, File f2) throws Exception { int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); ByteBuffer b = null; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); } if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else length = 2097152; b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } } /** * ? * * @param fileName * @return * @throws IOException */ public static boolean existFile(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { throw new IOException(":" + fileName); } return file.exists(); } /** * * * @param fileName */ public static void deleteFile(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { throw new IOException(":" + fileName); } file.delete(); } /** * ? * * @param fileName * @return * @throws IOException */ public static String readFile(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { throw new IOException(":" + fileName); } BufferedReader in = new BufferedReader(new FileReader(file)); StringBuffer sb = new StringBuffer(); String str = ""; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); return sb.toString(); } /** * ? * * @param fileName * @return * @throws IOException */ public static List<File> listFiles(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { throw new IOException(":" + fileName); } return Arrays.asList(file.listFiles()); } /** * * * @param dir */ public static void mkdir(String dir) { String dirTemp = dir; File dirPath = new File(dirTemp); if (!dirPath.exists()) { dirPath.mkdir(); } } /** * * * @param fileName * String ??? :E:\phsftp\src\123.txt * @param content * String */ public static void createNewFile(String fileName, String content) throws IOException { String fileNameTemp = fileName; File filePath = new File(fileNameTemp); if (!filePath.exists()) { filePath.createNewFile(); } FileWriter fw = new FileWriter(filePath); PrintWriter pw = new PrintWriter(fw); String strContent = content; pw.println(strContent); pw.flush(); pw.close(); fw.close(); } /** * * * @param folderPath * */ public static void delFolder(String folderPath) { // ? delAllFile(folderPath); String filePath = folderPath; java.io.File myFilePath = new java.io.File(filePath); // myFilePath.delete(); } /** * ? * * @param path * */ public static void delAllFile(String path) { File file = new File(path); if (!file.exists()) { return; } if (!file.isDirectory()) { return; } String[] childFiles = file.list(); File temp = null; for (int i = 0; i < childFiles.length; i++) { // File.separator?? // UNIX'/'Microsoft Windows '\' if (path.endsWith(File.separator)) { temp = new File(path + childFiles[i]); } else { temp = new File(path + File.separator + childFiles[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + File.separatorChar + childFiles[i]);// ? delFolder(path + File.separatorChar + childFiles[i]);// ? } } } /** * ??? * * @param srcFile * ?? E:/phsftp/src/abc.txt * @param dirDest * ? E:/phsftp/dest * @throws IOException */ public static void copyFile(String srcFile, String dirDest) throws IOException { FileInputStream in = new FileInputStream(srcFile); mkdir(dirDest); FileOutputStream out = new FileOutputStream(dirDest + "/" + new File(srcFile).getName()); int len; byte buffer[] = new byte[1024]; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); out.close(); in.close(); } /** * ? * * @param oldPath * String ? E:/phsftp/src * @param newPath * String E:/phsftp/dest * @return boolean */ public static void copyFolder(String oldPath, String newPath) throws IOException { // ? mkdir(newPath); File file = new File(oldPath); String[] files = file.list(); File temp = null; for (int i = 0; i < files.length; i++) { if (oldPath.endsWith(File.separator)) { temp = new File(oldPath + files[i]); } else { temp = new File(oldPath + File.separator + files[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString()); byte[] buffer = new byte[1024 * 2]; int len; while ((len = input.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {// ? copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]); } } } /** * * * @param oldPath * ??? E:/phsftp/src/ljq.txt * @param newPath * E:/phsftp/dest */ public static void moveFile(String oldPath, String newPath) throws IOException { copyFile(oldPath, newPath); deleteFile(oldPath); } /** * ? * * @param oldPath * ? E:/phsftp/src * @param newPath * E:/phsftp/dest */ public static void moveFiles(String oldPath, String newPath) throws IOException { copyFolder(oldPath, newPath); delAllFile(oldPath); } /** * * * @param oldPath * ? E:/phsftp/src * @param newPath * E:/phsftp/dest */ public static void moveFolder(String oldPath, String newPath) throws IOException { copyFolder(oldPath, newPath); delFolder(oldPath); } /** * zip * :?ZipOutputStreamZipInputStreamzip. * :java.util.zip??,zip??, * :"Exception in thread "main " java.lang.IllegalArgumentException * at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285) * @param srcDir * ? * @param destDir * ? * @throws Exception */ public static void unZip(String srcDir, String destDir) throws IOException { int leng = 0; byte[] b = new byte[1024 * 2]; /** ?zip? **/ File[] zipFiles = new ExtensionFileFilter("zip").getFiles(srcDir); if (zipFiles != null && !"".equals(zipFiles)) { for (int i = 0; i < zipFiles.length; i++) { File file = zipFiles[i]; /** ? * */ ZipInputStream zis = new ZipInputStream(new FileInputStream(file)); ZipEntry entry = null; while ((entry = zis.getNextEntry()) != null) { File destFile = null; if (destDir.endsWith(File.separator)) { destFile = new File(destDir + entry.getName()); } else { destFile = new File(destDir + File.separator + entry.getName()); } /** ? * */ FileOutputStream fos = new FileOutputStream(destFile); while ((leng = zis.read(b)) != -1) { fos.write(b, 0, leng); } fos.close(); } zis.close(); } } } /** * * :?ZipOutputStreamZipInputStreamzip. * :java.util.zip??,zip??, * :"Exception in thread "main " java.lang.IllegalArgumentException * at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285) * @param srcDir * ? * @param destDir * ? * @throws Exception */ public static void zip(String srcDir, String destDir) throws IOException { String tempFileName = null; byte[] buf = new byte[1024 * 2]; int len; // ?? File[] files = new File(srcDir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); if (destDir.endsWith(File.separator)) { tempFileName = destDir + file.getName() + ".zip"; } else { tempFileName = destDir + File.separator + file.getName() + ".zip"; } FileOutputStream fos = new FileOutputStream(tempFileName); BufferedOutputStream bos = new BufferedOutputStream(fos); ZipOutputStream zos = new ZipOutputStream(bos);// ZipEntry ze = new ZipEntry(file.getName());// ?? zos.putNextEntry(ze);// ZIP????? while ((len = bis.read(buf)) != -1) { zos.write(buf, 0, len); zos.flush(); } bis.close(); zos.close(); } } } } /** * ?? * * @param inSream * @param charsetName * @return * @throws Exception */ public static String readData(InputStream inSream, String charsetName) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inSream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); outStream.close(); inSream.close(); return new String(data, charsetName); } /** * ????? * * @param path * @return * @throws Exception */ public static Set<String> readFileLine(String path) throws IOException { Set<String> datas = new HashSet<String>(); FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { datas.add(line); } br.close(); fr.close(); return datas; } public static void main(String[] args) { try { unZip("c:/test", "c:/test"); } catch (IOException e) { e.printStackTrace(); } } public static String normalizeAbsolutePath(String path, boolean removeTrailingSlash) throws IllegalPathException { return normalizePath(path, true, false, removeTrailingSlash); } private static String normalizePath(String path, boolean forceAbsolute, boolean forceRelative, boolean removeTrailingSlash) throws IllegalPathException { char[] pathChars = StringUtils.trimToEmpty(path).toCharArray(); int length = pathChars.length; // ??path"/" boolean startsWithSlash = false; boolean endsWithSlash = false; if (length > 0) { char firstChar = pathChars[0]; char lastChar = pathChars[length - 1]; startsWithSlash = firstChar == '/' || firstChar == '\\'; endsWithSlash = lastChar == '/' || lastChar == '\\'; } StringBuilder buf = new StringBuilder(length); boolean isAbsolutePath = forceAbsolute || !forceRelative && startsWithSlash; int index = startsWithSlash ? 0 : -1; int level = 0; if (isAbsolutePath) { buf.append("/"); } while (index < length) { // ?slash index = indexOfSlash(pathChars, index + 1, false); if (index == length) { break; } // ?slash index int nextSlashIndex = indexOfSlash(pathChars, index, true); String element = new String(pathChars, index, nextSlashIndex - index); index = nextSlashIndex; // "." if (".".equals(element)) { continue; } // ".." if ("..".equals(element)) { if (level == 0) { // ?../?? // ? if (isAbsolutePath) { throw new IllegalPathException(path); } else { buf.append("../"); } } else { buf.setLength(pathChars[--level]); } continue; } // path pathChars[level++] = (char) buf.length(); // ?charslevelindex buf.append(element).append('/'); } // ?"/" if (buf.length() > 0) { if (!endsWithSlash || removeTrailingSlash) { buf.setLength(buf.length() - 1); } } return buf.toString(); } private static int indexOfSlash(char[] chars, int beginIndex, boolean slash) { int i = beginIndex; for (; i < chars.length; i++) { char ch = chars[i]; if (slash) { if (ch == '/' || ch == '\\') { break; // if a slash } } else { if (ch != '/' && ch != '\\') { break; // if not a slash } } } return i; } } class ExtensionFileFilter implements FileFilter { private final String extension; public ExtensionFileFilter(String extension) { this.extension = extension; } public File[] getFiles(String srcDir) throws IOException { return (File[]) Files.listFiles(srcDir).toArray(); } @Override public boolean accept(File file) { if (file.isDirectory()) { return false; } String name = file.getName(); // find the last int idx = name.lastIndexOf("."); if (idx == -1) { return false; } else if (idx == name.length() - 1) { return false; } else { return this.extension.equals(name.substring(idx + 1)); } } }