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.sunchenbin.store.feilong.core.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sunchenbin.store.feilong.core.bean.ConvertUtil; import com.sunchenbin.store.feilong.core.util.Validator; /** * {@link File}?. * * <h3>File:</h3> * * <blockquote> * <ul> * <li>{@link File#getAbsolutePath()} </li> * <li>{@link File#getPath()} file</li> * <li>{@link File#getCanonicalPath()} ?CanonicalPath?,...???.</li> * </ul> * </blockquote> * * * <h3>?:</h3> * * <blockquote> * <ul> * <li>{@link FileUtils#ONE_KB} 1024</li> * <li>{@link FileUtils#ONE_MB} 1024 * 1024 1048576</li> * <li>{@link FileUtils#ONE_GB} 1024 * 1024 * 1024 1073741824 * <p style="color:red"> * <b>?,{@link Integer#MAX_VALUE}=2147483647 2G?</b> * </p> * </ul> * </blockquote> * * @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 * @see org.apache.commons.io.FilenameUtils * @see org.apache.commons.io.FileUtils * @since 1.0.0 */ public final class FileUtil { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class); /** ? 10k <code>{@value}</code>. */ public static final int DEFAULT_BUFFER_LENGTH = (int) (10 * FileUtils.ONE_KB); /** 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 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 #getFileInputStream(File) * @see java.io.ByteArrayOutputStream#toByteArray() * @see org.apache.commons.io.FileUtils#readFileToByteArray(File) * @see org.apache.commons.io.IOUtils#toByteArray(InputStream, int) */ public static byte[] toByteArray(File file) { InputStream inputStream = getFileInputStream(file); try { return IOUtils.toByteArray(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } finally { // ???,StreamClose.??,Close, IOUtils.closeQuietly(inputStream); } } //******************************************************************************* /** * {@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 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 FileOutputStream getFileOutputStream(String filePath, FileWriteMode fileWriteMode) { boolean append = fileWriteMode == FileWriteMode.APPEND; return getFileOutputStream(filePath, append); } /** * {@link java.io.FileOutputStream} ? . * * <p> * {@link java.io.FileOutputStream} ???.<br> * ??, {@link java.io.FileWriter}. * </p> * * @param filePath * the file path * @param append * if {@code true}, then bytes will be added to the end of the file rather than overwriting * @return the file output stream * @see java.io.FileOutputStream#FileOutputStream(String, boolean) * @see org.apache.commons.io.FileUtils#openOutputStream(File, boolean) * @since 1.2.0 */ // Access Modifiers ?? static FileOutputStream getFileOutputStream(String filePath, boolean append) { File file = new File(filePath); return getFileOutputStream(file, append); } /** * {@link java.io.FileOutputStream} ? . * * <p> * {@link java.io.FileOutputStream} ???.<br> * ??, {@link java.io.FileWriter}. * </p> * * @param file * the file * @param append * if {@code true}, then bytes will be added to the end of the file rather than overwriting * @return the file output stream * @since 1.4.0 */ // Access Modifiers ?? static FileOutputStream getFileOutputStream(File file, boolean append) { try { return org.apache.commons.io.FileUtils.openOutputStream(file, append); } catch (IOException 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 FileInputStream getFileInputStream(String fileName) { File file = new File(fileName); return getFileInputStream(file); } /** * ?.??. * * <p> * {@link java.io.FileInputStream} ????.<br> * ???, {@link java.io.FileReader} * </p> * * <p> * ?;,?;??, FileNotFoundException * </p> * * @param file * ?. * @return FileInputStream * @see org.apache.commons.io.FileUtils#openInputStream(File) */ public static FileInputStream getFileInputStream(File file) { try { return org.apache.commons.io.FileUtils.openInputStream(file); } catch (IOException e) { LOGGER.error("", e); throw new UncheckedIOException(e); } } /** * ? <span style="color:red">(:?)</span>. * * @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> * @see org.apache.commons.io.FileUtils#sizeOf(File) * @see org.apache.commons.io.FileUtils#sizeOfDirectory(File) */ 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 File[] listFiles = file.listFiles(); int fileListLength = listFiles.length; if (LOGGER.isDebugEnabled()) { LOGGER.debug("file :[{}] list length:[{}]", directory, fileListLength); for (File tempFile : listFiles) { LOGGER.debug("[{}] [{}]", tempFile.getName(), tempFile.isDirectory() ? FileType.DIRECTORY : FileType.FILE); } } return 0 == fileListLength; } // [start] ?(createDirectory/deleteFileOrDirectory/deleteFileOrDirectory) /** * by,??. * * <h3>?:</h3> * * <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); } /** * ,?<span style="color:green">?</span>. * * <h3>?:</h3> * * <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); } //? LOGGER.debug("success mkdirs:[{}]~~", absolutePath); } /** * , , . * * <p> * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * </p> * * <h3>difference between {@link File#delete()} and current method:</h3> * * <blockquote> * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * </blockquote> * * @param fileName * ?? * @return {@code true} if the file or directory was deleted, otherwise {@code false} * @see com.sunchenbin.store.feilong.core.io.FileUtil#deleteFileOrDirectory(File) */ public static boolean deleteFileOrDirectory(String fileName) { File file = new File(fileName); return deleteFileOrDirectory(file); } /** * , , . * * <p> * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * </p> * * <h3>difference between {@link File#delete()} and current method:</h3> * * <blockquote> * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * </blockquote> * * @param file * file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise {@code false} * * @see org.apache.commons.io.FileUtils#deleteQuietly(File) */ public static boolean deleteFileOrDirectory(File file) { return FileUtils.deleteQuietly(file); } // [end] // ************************************************************ /** * ??????, 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); return file.getParent(); } /** * ?. * * @param filePath * the file path * @return ,true */ public static 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 boolean isNotExistFile(String filePath) { return !isExistFile(filePath); } // ************************************************************ /** * ??. * * <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 com.sunchenbin.store.feilong.core.io.FileUtil#formatSize(long) * @see org.apache.commons.io.FileUtils#byteCountToDisplaySize(long) * @since 1.0.7 */ public static String getFileFormatSize(File file) { if (Validator.isNullOrEmpty(file)) { throw new NullPointerException("file can't be null/empty!"); } long fileSize = getFileSize(file); return formatSize(fileSize); } /** * ??. * * <p> * ???? GB MB KB???? Bytes * </p> * * <p> * Common-io 2.4{@link org.apache.commons.io.FileUtils#byteCountToDisplaySize(long)},GB ??1.99G 1G,apache ? * </p> * * @param fileSize * ? ??byte * @return ?byte ? * @see #getFileSize(File) * @see org.apache.commons.io.FileUtils#ONE_GB * @see org.apache.commons.io.FileUtils#ONE_MB * @see org.apache.commons.io.FileUtils#ONE_KB * * @see org.apache.commons.io.FileUtils#byteCountToDisplaySize(long) */ public static String formatSize(long fileSize) { String danwei = ""; long chushu = 1;// if (fileSize >= FileUtils.ONE_GB) { danwei = "GB"; chushu = FileUtils.ONE_GB; } else if (fileSize >= FileUtils.ONE_MB) { danwei = "MB"; chushu = FileUtils.ONE_MB; } else if (fileSize >= FileUtils.ONE_KB) { danwei = "KB"; chushu = FileUtils.ONE_KB; } else { return fileSize + "Bytes"; } String yushu = 100 * (fileSize % chushu) / chushu + ""; // ? if ("0".equals(yushu)) { return fileSize / chushu + danwei; } return fileSize / chushu + "." + yushu + danwei; } /** * ??(??). * * @param file * * @return ??,??<br> * ?, 0L.<br> * ???,??? 0L. * @see File#length() */ public static long getFileSize(File file) { return file.length(); } /** * To ur ls. * * @param filePathList * the paths * @return the UR l[] * @see #toURLs(String...) * @since 1.4.0 */ public static URL[] toURLs(List<String> filePathList) { if (Validator.isNullOrEmpty(filePathList)) { throw new NullPointerException("paths can't be null/empty!"); } String[] filePaths = ConvertUtil.toArray(filePathList, String.class); return toURLs(filePaths); } /** * To ur ls. * * @param filePaths * the file paths * @return the UR l[] * @see com.sunchenbin.store.feilong.core.bean.ConvertUtil#convert(String[], Class) * @see org.apache.commons.io.FileUtils#toURLs(File[]) * @since 1.4.0 */ public static URL[] toURLs(String... filePaths) { if (Validator.isNullOrEmpty(filePaths)) { throw new NullPointerException("paths can't be null/empty!"); } File[] files = ConvertUtil.convert(filePaths, File.class); try { return org.apache.commons.io.FileUtils.toURLs(files); } catch (IOException e) { LOGGER.error("", e); throw new UncheckedIOException(e); } } }