Java tutorial
/* * Copyright (C) 2008 feilong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.discovery.darchrow.io; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.discovery.darchrow.lang.ArrayUtil; import com.discovery.darchrow.util.Validator; /** * {@link File}?.<br> * * File: * <ul> * <li>{@link File#getAbsolutePath()} </li> * <li>{@link File#getPath()} file</li> * <li>{@link File#getCanonicalPath()} ?CanonicalPath?...???.</li> * </ul> * * @author feilong * @version 1.0.0 2012-5-23 ?5:00:54 * @version 1.0.7 2014-5-23 20:27 add {@link #getFileFormatSize(File)} * @see java.io.File * @since 1.0.0 */ public final class FileUtil { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class); /** Don't let anyone instantiate this class. */ private FileUtil() { //AssertionError?. ?????. ???. //see Effective Java 2nd throw new AssertionError("No " + getClass().getName() + " instances for you!"); } /** * ? {@code byte[] bytes}. * * @param fileName * the file name * @return {@link java.io.ByteArrayOutputStream#toByteArray()} * @see #toByteArray(File) * @since 1.2.1 */ public static final byte[] toByteArray(String fileName) { File file = new File(fileName); return toByteArray(file); } /** * ? {@code byte[] bytes}. * * @param file * file * @return {@link java.io.ByteArrayOutputStream#toByteArray()} * @see com.baozun.nebulaplus.io.FileUtil#getFileInputStream(File) * @see java.io.ByteArrayOutputStream#toByteArray() */ public static final byte[] toByteArray(File file) { InputStream inputStream = getFileInputStream(file); //Creates a BufferedInputStream and saves its argument, the input stream in, for later use. //An internal buffer array is created and stored in buf. BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); //Creates a new byte array output stream. //The buffer capacity is initially 32 bytes, though its size increases if necessary. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byte[] bytes = new byte[IOConstants.DEFAULT_BUFFER_LENGTH]; int j; while ((j = bufferedInputStream.read(bytes)) != -1) { byteArrayOutputStream.write(bytes, 0, j); } byteArrayOutputStream.flush(); byte[] byteArray = byteArrayOutputStream.toByteArray(); return byteArray; } catch (IOException e) { throw new UncheckedIOException(e); } finally { // ???StreamClose.??Close IOUtils.closeQuietly(byteArrayOutputStream); IOUtils.closeQuietly(bufferedInputStream); } } //******************************************************************************* /** * {@link java.io.FileOutputStream} ? .<br> * {@link java.io.FileOutputStream} ???.<br> * ?? {@link java.io.FileWriter}. * * @param filePath * * @return FileOutputStream * @see java.io.FileOutputStream#FileOutputStream(String) * @see #getFileOutputStream(String, boolean) */ public static final FileOutputStream getFileOutputStream(String filePath) { // append false return getFileOutputStream(filePath, false); } /** * {@link java.io.FileOutputStream} ? .<br> * {@link java.io.FileOutputStream} ???.<br> * ?? {@link java.io.FileWriter}. * * @param filePath * the file path * @param fileWriteMode * the file write mode * @return the file output stream * @see #getFileOutputStream(String, boolean) * @since 1.2.0 */ public static final FileOutputStream getFileOutputStream(String filePath, FileWriteMode fileWriteMode) { boolean append = (fileWriteMode == FileWriteMode.APPEND); return getFileOutputStream(filePath, append); } /** * {@link java.io.FileOutputStream} ? .<br> * {@link java.io.FileOutputStream} ???.<br> * ?? {@link java.io.FileWriter}. * * @param filePath * the file path * @param append * if true, then bytes will be written to the end of the file rather than the beginning * @return the file output stream * @see java.io.FileOutputStream#FileOutputStream(String, boolean) * @since 1.2.0 */ // Access Modifiers ?? static final FileOutputStream getFileOutputStream(String filePath, boolean append) { try { FileOutputStream fileOutputStream = new FileOutputStream(filePath, append); return fileOutputStream; } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } } //******************************************************************************************** /** * ?.??.<br> * {@link java.io.FileInputStream} ????.<br> * ??? {@link java.io.FileReader} * * @param fileName * ?? fileName . * @return FileInputStream * @see #getFileInputStream(File) */ public static final FileInputStream getFileInputStream(String fileName) { File file = new File(fileName); return getFileInputStream(file); } /** * ?.??.<br> * {@link java.io.FileInputStream} ????.<br> * ??? {@link java.io.FileReader} * * @param file * ?. * @return FileInputStream * @see java.io.FileInputStream */ public static final FileInputStream getFileInputStream(File file) { try { // ???? FileNotFoundException. FileInputStream fileInputStream = new FileInputStream(file); return fileInputStream; } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } } /** * ?(?). * * @param directory * * @return <ul> * <li>directory isNullOrEmpty,throw IllegalArgumentException</li> * <li>directory don't exists,throw IllegalArgumentException</li> * <li>directory is not Directory,throw IllegalArgumentException</li> * <li>return file.list() ==0</li> * </ul> */ public static boolean isEmptyDirectory(String directory) { if (Validator.isNullOrEmpty(directory)) { throw new NullPointerException("directory param " + directory + " can't be null/empty!"); } File file = new File(directory); if (!file.exists()) { throw new IllegalArgumentException("directory file " + directory + " don't exists!"); } if (!file.isDirectory()) { throw new IllegalArgumentException("directory file " + directory + " is not Directory!"); } // Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. // ??? null // ubuntu ? ok String[] fileList = file.list(); int fileListLength = fileList.length; if (LOGGER.isDebugEnabled()) { LOGGER.debug("file :[{}] list length:[{}]", directory, fileListLength); for (String fileName : fileList) { LOGGER.debug(fileName); } } boolean flag = (fileListLength == 0); return flag; } // [start] ?(createDirectory/deleteFileOrDirectory/deleteFileOrDirectory) /** * by,??.<br> * * ?: * <ol> * <li><span style="color:red">?</span>,?, {@link #createDirectory(String)}</li> * <li>?/: "E:\\test\\1\\2011-07-07" , ?</li> * <li>{@link File#isDirectory()} , ?</li> * </ol> * * <h3>??:</h3> * * <blockquote> * <ol> * <li>{@code if isNullOrEmpty(filePath)---->NullPointerException}</li> * <li>{@link #getParent(String) getParent}(filePath)</li> * <li>{@link #createDirectory(String) createDirectory}(directory)</li> * </ol> * </blockquote> * * @param filePath * <span style="color:red"></span> * @see #getParent(String) * @see #createDirectory(String) * @since 1.2.0 */ public static void createDirectoryByFilePath(String filePath) { if (Validator.isNullOrEmpty(filePath)) { throw new NullPointerException("filePath can't be null/empty!"); } String directory = getParent(filePath); createDirectory(directory); } /** * ,??. * * <p> * ?: * </p> * <ol> * <li><span style="color:red">?</span>,?, {@link #createDirectoryByFilePath(String)}</li> * <li>?/: "E:\\test\\1\\2011-07-07" , ?</li> * <li>{@link File#isDirectory()} , ?</li> * </ol> * * <h3>??:</h3> <blockquote> * <ol> * <li>{@code if Validator.isNullOrEmpty(directory)---->NullPointerException}</li> * <li>{@code if directory exists---->log debug and return}</li> * <li>{@link java.io.File#mkdirs()}</li> * <li>{@code if mkdirs's result is false ---> return IllegalArgumentException}</li> * <li>{@code if mkdirs's result is true ---> log debug}</li> * </ol> * </blockquote> * * @param directory * <span style="color:red"></span> * @see #createDirectoryByFilePath(String) */ public static void createDirectory(String directory) { if (Validator.isNullOrEmpty(directory)) { throw new NullPointerException("filePath can't be null/empty!"); } File directoryFile = new File(directory); boolean isExists = directoryFile.exists(); //***********do with ****************** if (isExists) {// LOGGER.debug("exists directoryFile:[{}],don't need mkdirs,nothing to do~", directoryFile); return; } //***********do with ?****************** String absolutePath = directoryFile.getAbsolutePath(); // mkdir parent ? false ? boolean flag = directoryFile.mkdirs(); // ? if (!flag) { String msg = "File [" + absolutePath + "] could not be created"; LOGGER.error(msg); throw new IllegalArgumentException(msg); } else { //? LOGGER.debug("success mkdirs:[{}]~~", absolutePath); } } /** * ?. * * @param fileName * ?? */ public static void deleteFileOrDirectory(String fileName) { File file = new File(fileName); if (file.exists()) { deleteFileOrDirectory(file); } throw new IllegalArgumentException("file:[" + fileName + "] not exists,please check it!"); } /** * , , . * * @param file * ?? */ public static void deleteFileOrDirectory(File file) { if (file.exists() && file.isDirectory()) { File[] files = file.listFiles(); if (null != files && files.length > 0) { for (File currentFile : files) { if (!currentFile.isDirectory()) { currentFile.delete(); } else { deleteFileOrDirectory(currentFile); } } } file.delete(); } else { file.delete(); } } // [end] // ************************************************************ // [start] ??? /** * ?,?? * <p> * ?, .+newPostfixName * </p> * * <pre> * {@code * Example 1: * String fileName="F:/pie2.png"; * FileUtil.getNewFileName(fileName, "gif") * * return F:/pie2.gif * } * </pre> * * @param fileName * ??, F:/pie2.png * @param newPostfixName * ?.?, gif * @return ?? */ public static final String getNewFileName(String fileName, String newPostfixName) { if (Validator.isNullOrEmpty(fileName)) { throw new NullPointerException("fileName can't be null/empty!"); } if (Validator.isNullOrEmpty(newPostfixName)) { throw new NullPointerException("newPostfixName can't be null/empty!"); } // ? if (hasPostfixName(fileName)) { return fileName.substring(0, fileName.lastIndexOf(".") + 1) + newPostfixName; } // ? return fileName + "." + newPostfixName; } /** * ??. * * @param fileName * the file name * @return true, if successful */ public static final boolean hasPostfixName(String fileName) { String fileNameString = getFileName(fileName); int lastIndexOf = fileNameString.lastIndexOf("."); if (-1 == lastIndexOf) { return false; } return true; } /** * ???(?. ?),?<br> * ??? "" (EMPTY). * * <pre> * {@code * Example 1: * F:/pie2.png, return png * * Example 2: * F:/pie2, return "" * } * </pre> * * @param fileName * ?? * @return ?. ? * @see org.apache.commons.io.FilenameUtils#getExtension(String) * @see java.lang.String#substring(int, int) */ public static final String getFilePostfixName(String fileName) { if (hasPostfixName(fileName)) { String filePostfixName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); return filePostfixName; } return ""; } /** * ???,??<br> * ??? "". * * @param fileName * ?? * @return ?. ? * @see org.apache.commons.io.FilenameUtils#getExtension(String) */ public static final String getFilePostfixNameLowerCase(String fileName) { String postfixName = getFilePostfixName(fileName); return postfixName.toLowerCase(); } /** * ??????. <br> * * <pre> * {@code * Example 1: * F:/pie2.png, return F:/pie2 * * Example 2: * pie2.png, return pie2 * } * </pre> * * @param fileName * ?? * @return ?????? * @see java.lang.String#substring(int, int) */ public static final String getFilePreName(String fileName) { return fileName.substring(0, fileName.lastIndexOf(".")); } /** * ???<br> * :F:/pie2.png,return pie2.png * * @param fileName * the file name * @return the file name * @see java.io.File#getName() */ public static final String getFileName(String fileName) { File file = new File(fileName); return file.getName(); } // [end] /** * ?? * * <pre> * {@code * Example 1: * "mp2-product\\mp2-product-impl\\src\\main\\java\\com\\baozun\\mp2\\rpc\\impl\\item\\repo\\package-info.java" * * mp2-product * } * </pre> * * @param pathname * ?????? File .??. * @return ,, E:/ E:/ * @since 1.0.7 */ public static final String getFileTopParentName(String pathname) { if (Validator.isNullOrEmpty(pathname)) { throw new NullPointerException("pathname can't be null/empty!"); } File file = new File(pathname); String parent = file.getParent(); if (Validator.isNullOrEmpty(parent)) { return pathname; } // String fileTopParentName = getFileTopParentName(file); if (LOGGER.isDebugEnabled()) { LOGGER.debug("pathname:[{}],fileTopParentName:[{}]", pathname, fileTopParentName); } return fileTopParentName; } /** * ?????? null. * * @param path * the path * @return the parent * @see java.io.File#getParent() */ public static String getParent(String path) { if (Validator.isNullOrEmpty(path)) { throw new NullPointerException("pathname can't be null/empty!"); } File file = new File(path); String parent = file.getParent(); return parent; } /** * ?? * * <pre> * {@code * Example 1: * "mp2-product\\mp2-product-impl\\src\\main\\java\\com\\baozun\\mp2\\rpc\\impl\\item\\repo\\package-info.java" * * mp2-product * } * </pre> * * @param file * the file * @return ,, E:/ E:/ * @since 1.0.7 */ public static final String getFileTopParentName(File file) { if (Validator.isNullOrEmpty(file)) { throw new NullPointerException("file can't be null/empty!"); } File parent = file.getParentFile(); if (Validator.isNullOrEmpty(parent)) { String name = file.getPath();//E:/--->E:\ if (LOGGER.isDebugEnabled()) { LOGGER.debug("parent is isNullOrEmpty,return file name:{}", name); } return name; } // String fileTopParentName = getFileTopParentName(parent); if (LOGGER.isDebugEnabled()) { LOGGER.debug("file.getAbsolutePath():[{}],fileTopParentName:[{}]", file.getAbsolutePath(), fileTopParentName); } return fileTopParentName; } /** * ?. * * @param filePath * the file path * @return ,true */ public static final boolean isExistFile(String filePath) { File file = new File(filePath); return file.exists(); } /** * ?. * * @param filePath * the file path * @return ?,true * @since 1.0.3 */ public static final boolean isNotExistFile(String filePath) { return !isExistFile(filePath); } // ************************************************************************ // // ?? // // ************************************************************************ /** * ??. * * @param fileName * ??,? ,? ,????? * @return ?? */ public static final boolean isCommonImage(String fileName) { return isInAppointTypes(fileName, COMMON_IMAGES); } /** * ??. * * @param fileName * ?? * @param appointTypes * * @return ?? */ // XXX ? public static final boolean isInAppointTypes(String fileName, String[] appointTypes) { return ArrayUtil.isContain(appointTypes, getFilePostfixName(fileName)); } // ************************************************************ /** * ??. * <p> * ???? GB MB KB???? Bytes * </p> * <p> * Common-io 2.4{@link org.apache.commons.io.FileUtils#byteCountToDisplaySize(long)}GB ??1.99G 1Gapache ? * </p> * * @param fileSize * ? ??byte * @return ?byte ? * @see #getFileSize(File) * @see IOConstants#GB * @see IOConstants#MB * @see IOConstants#KB * * @see org.apache.commons.io.FileUtils#byteCountToDisplaySize(long) */ public static final String formatSize(long fileSize) { String danwei = "Bytes"; // ? String yushu = ""; // long chushu = 1; if (fileSize >= IOConstants.GB) { danwei = "GB"; chushu = IOConstants.GB; } else if (fileSize >= IOConstants.MB) { danwei = "MB"; chushu = IOConstants.MB; } else if (fileSize >= IOConstants.KB) { danwei = "KB"; chushu = IOConstants.KB; } if (chushu == 1) { return fileSize + danwei; } yushu = 100 * (fileSize % chushu) / chushu + ""; if ("0".equals(yushu)) { return fileSize / chushu + danwei; } return fileSize / chushu + "." + yushu + danwei; } /** * ??. * * <p> * 3834,?? 3.74KB<br> * 36830335 , ??:35.12MB<br> * 2613122669 , ?? : 2.43GB<br> * </p> * * <p> * ???? GB MB KB???? Bytes * </p> * * @param file * the file * @return the file format size * @see #getFileSize(File) * @see IOConstants#GB * @see IOConstants#MB * @see IOConstants#KB * @see org.apache.commons.io.FileUtils#byteCountToDisplaySize(long) * @since 1.0.7 */ public static final String getFileFormatSize(File file) { if (Validator.isNullOrEmpty(file)) { throw new NullPointerException("file can't be null/empty!"); } long fileSize = getFileSize(file); return formatSize(fileSize); } /** * ??(??). * * @param file * * @return ????<br> * ? 0L.<br> * ?????? 0L. * @see File#length() */ public static long getFileSize(File file) { return file.length(); } /** * ??? ???,???. * * @param fileName * ?? * @return ??? * @see #MICROSOFT_PC * @since 1.0.7 */ public static String getFormatFileName(final String fileName) { String formatFileName = fileName; for (int i = 0, j = MICROSOFT_PC.length; i < j; ++i) { String[] arrayElement = MICROSOFT_PC[i]; String oldChar = arrayElement[0]; String newChar = arrayElement[1]; if (formatFileName.contains(oldChar)) { LOGGER.warn("formatFileName:[{}] contains oldChar:[{}],will replace newChar:[{}]", formatFileName, oldChar, newChar); formatFileName = formatFileName.replace(oldChar, newChar); } } return formatFileName; } /** * ??????????? . * <p> * Windows ?? 255 <br> * DOS ?? 8 ?? 3 ? DOS 8.3 ??. <br> * ?????,?????? 1 ? ? C ? . <br> * ??? * </p> * <ul> * <li>???? 9 \/:*?"<>|</li> * <li>?? ?? ? ??. ?? ? con aux com0 ~ com9 lpt0 ~ lpt9 nul prn</li> * <li>???? A.txt a.TxT ?</li> * </ul> * * @see <a href="http://support.microsoft.com/kb/177506/zh-cn">? ????</a> * @since 1.0.7 */ private static final String[][] MICROSOFT_PC = { // // { "\\", "" }, // \ // { "/", "" }, // / { "\"", "" }, // " { ":", "" }, // : { "*", "" }, // * { "?", "" }, // ? { "<", "" }, // < { ">", "" }, // > { "|", "" }, // | }; /** * ?. * * @deprecated ?,? */ @Deprecated private static final String[] COMMON_IMAGES = { "gif", "bmp", "jpg", "png" }; }