commons-io FileUtils Helper

commons-io主要对输入流,输出流的打开和关闭,主要是对文件的copy, 字符串到文件的传输, 其实这个功能对IO的封装还是不错的,我们就不用自己去打开输入流和输出流。

package org.ycl.commons.text;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.nio.channels.FileChannel;

import org.apache.commons.io.IOUtils;
 
/**
 * 
 * 1. stringToFile/fileToString
 * <li>- read String to File, or reserve</li>
 * 2. moveFile
 * <li>- If we process this file, will be move to archive directory</li>
 * 3. getTempDirectory/getUserDirectory
 * <li>- return "java.io.tmpdir", "user.home" derectory</li>
 * 4. openInputStream
 * <li>- open file in InputStream with safe method</li>
 * 5. openOutputStream
 * <li>- Open out put file in safe method, if parent path is not exists, create it.</li>
 * 6. byteCountToDisplaySize
 * <li>- get the File Size in human readable.</li>
 * 7. touch
 * <li>- just open File, modify the date without modify content</li>
 * 8. copyFile(File srcFile, File destFile)
 * <li>- preserve file modify date is true.</li>
 * 
 * NOTE:this is from my tool box
 * {@link org.apache.commons.io.FileUtils} 
 *
 */
public class FileUtils { 
	 /**
     * The number of bytes in a kilobyte.
     */
    public static final long ONE_KB = 1024;
	
	 /**
     * The number of bytes in a megabyte.
     */
    public static final long ONE_MB = ONE_KB * ONE_KB;
    /**
     * The file copy buffer size (30 MB)
     */
    private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30;
    
    public static long MAXFILESIZE = ONE_MB * 25;//25MB

	/**
	 * write String to file.
	 * 
	 * @param file
	 * @param fileContent
	 * @throws IOException
	 */
	public static void stringToFile(File file, String fileContent) throws IOException{
		if(file != null && !file.isDirectory())
		{
			if (!file.isFile())
				file.createNewFile();
			FileOutputStream fs = null;
			fs = new FileOutputStream(file); 
			if (fs != null && fileContent!=null && fileContent.length()!=0) { 
				if (fileContent.length() > MAXFILESIZE)
					throw new RuntimeException("The size of file "
							+ file.getName() + " can't exceed " + MAXFILESIZE
							+ " bytes"); 
				fs.write(fileContent.getBytes());
				fs.flush();
			}
			fs.close();
		} else if (file != null && file.isDirectory()){
			throw new RuntimeException(file.getName() + " is a directory.");
		}else {
			throw new RuntimeException("The target file is null.");
		}
	}	
	
	/**
	 * read file from disk and convert it to a string
	 * 
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws PLMInterfaceAppException 
	 */
	public static String fileToString(File file) throws IOException{
		String fileString = null;
		if(file != null && file.isFile())
		{
			FileInputStream fs = null;
			fs = new FileInputStream(file);
		
			if (fs != null) {
				long filesize = file.length();
				if (filesize > MAXFILESIZE)
					throw new RuntimeException("The size of file "
							+ file.getName() + " exceeds " + MAXFILESIZE
							+ " bytes");
				byte[] content = new byte[(int)filesize];
				fs.read(content); 
				fileString = new String(content);
				fs.close();
			}
		}
		return fileString;
	}
	
	/**
	 * read file from disk and convert it to a string
	 * 
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws PLMInterfaceAppException 
	 */
	public static String fileToString(File file,String encode) throws IOException{ 
		StringBuffer sb = new StringBuffer();
		if(file != null && file.isFile())
		{ 
			FileInputStream fs = new FileInputStream(file);
			BufferedReader in= new BufferedReader(new InputStreamReader(fs,encode)); 
			if (in != null) {
				String inputLine;
				while ((inputLine = in.readLine()) != null) { 
					sb.append(inputLine);
				}
			}
			in.close();
		}
		return sb.toString();
	}
	
	/**
	 * move file to target folder
	 * 
	 * @param inFile
	 * @param folder
	 * @throws Exception
	 */
	public static void moveFile(File inFile, String folder) throws Exception {
		
		try {
		    String inFileName = inFile.getName();
		    
		    // ensure folder has trailing "/"
		    folder = folder.trim();
		    if (folder.lastIndexOf("/")+1 != folder.length()) {
		    	folder = folder + "/";
		    }	    
		    
		    File file2 = new File(folder+inFileName);
	
		    // Rename file
		    renameFile(inFile,file2);

	    } catch (Exception e) {
	    	throw e;
	    }
	}
	
	public static void renameFile(File inFile, File outFile) throws Exception {
		
		try {
		    if(outFile.exists()) throw new IOException("file already exists: " + outFile);
	
		    // Rename file
		    boolean success = inFile.renameTo(outFile);
		    if (!success) {
		        // File was not successfully renamed
		    	throw new Exception("Unable to rename file to: " +outFile);
		    }
	    } catch (Exception e) {
	    	throw e;
	    }
	}
	
	 /**
     * Returns the path to the system temporary directory.
     * 
     * @return the path to the system temporary directory.
     * 
     * @since 2.0
     */
    public static String getTempDirectoryPath() {
        return System.getProperty("java.io.tmpdir");
    }
    
    /**
     * Returns a {@link File} representing the system temporary directory.
     * 
     * @return the system temporary directory. 
     * 
     * @since 2.0
     */
    public static File getTempDirectory() {
        return new File(getTempDirectoryPath());
    }
    
    /**
     * Returns the path to the user's home directory.
     * 
     * @return the path to the user's home directory.
     * 
     * @since 2.0
     */
    public static String getUserDirectoryPath() {
        return System.getProperty("user.home");
    }
    
    /**
     * Returns a {@link File} representing the user's home directory.
     * 
     * @return the user's home directory.
     * 
     * @since 2.0
     */
    public static File getUserDirectory() {
        return new File(getUserDirectoryPath());
    }
    
    /**
     * Opens a {@link FileInputStream} for the specified file, providing better
     * error messages than simply calling <code>new FileInputStream(file)</code>.
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * An exception is thrown if the file does not exist.
     * An exception is thrown if the file object exists but is a directory.
     * An exception is thrown if the file exists but cannot be read.
     * 
     * @param file  the file to open for input, must not be {@code null}
     * @return a new {@link FileInputStream} for the specified file
     * @throws FileNotFoundException if the file does not exist
     * @throws IOException if the file object is a directory
     * @throws IOException if the file cannot be read
     * @since 1.3
     */
    public static FileInputStream openInputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canRead() == false) {
                throw new IOException("File '" + file + "' cannot be read");
            }
        } else {
            throw new FileNotFoundException("File '" + file + "' does not exist");
        }
        return new FileInputStream(file);
    }
     
    
    /**
     * Opens a {@link FileOutputStream} for the specified file, checking and
     * creating the parent directory if it does not exist.
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * The parent directory will be created if it does not exist.
     * The file will be created if it does not exist.
     * An exception is thrown if the file object exists but is a directory.
     * An exception is thrown if the file exists but cannot be written to.
     * An exception is thrown if the parent directory cannot be created.
     * 
     * @param file  the file to open for output, must not be {@code null}
     * @return a new {@link FileOutputStream} for the specified file
     * @throws IOException if the file object is a directory
     * @throws IOException if the file cannot be written to
     * @throws IOException if a parent directory needs creating but that fails
     * @since 1.3
     */
    public static FileOutputStream openOutputStream(File file) throws IOException {
        return openOutputStream(file, false);
    }

    /**
     * Opens a {@link FileOutputStream} for the specified file, checking and
     * creating the parent directory if it does not exist.
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * The parent directory will be created if it does not exist.
     * The file will be created if it does not exist.
     * An exception is thrown if the file object exists but is a directory.
     * An exception is thrown if the file exists but cannot be written to.
     * An exception is thrown if the parent directory cannot be created.
     * 
     * @param file  the file to open for output, must not be {@code null}
     * @param append if {@code true}, then bytes will be added to the
     * end of the file rather than overwriting
     * @return a new {@link FileOutputStream} for the specified file
     * @throws IOException if the file object is a directory
     * @throws IOException if the file cannot be written to
     * @throws IOException if a parent directory needs creating but that fails
     * @since 2.1
     */
    public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent + "' could not be created");
                }
            }
        }
        return new FileOutputStream(file, append);
    }
    
    /**
     * Returns a human-readable version of the file size, where the input represents a specific number of bytes.
     * <p>
     * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the
     * nearest GB boundary.
     * </p>
     * <p>
     * Similarly for the 1MB and 1KB boundaries.
     * </p>
     * 
     * @param size
     *            the number of bytes
     * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
     * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a>
     * @since 2.4
     */
    // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed?
    public static String byteCountToDisplaySize(BigInteger size) { 
        return org.apache.commons.io.FileUtils.byteCountToDisplaySize(size);
    }
    /**
     * Returns a human-readable version of the file size, where the input represents a specific number of bytes.
     * <p>
     * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the
     * nearest GB boundary.
     * </p>
     * <p>
     * Similarly for the 1MB and 1KB boundaries.
     * </p>
     * 
     * @param size
     *            the number of bytes
     * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
     * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a>
     */
    // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed?
    public static String byteCountToDisplaySize(long size) {
        return byteCountToDisplaySize(BigInteger.valueOf(size));
    }
    
    /**
     * Implements the same behaviour as the "touch" utility on Unix. It creates
     * a new file with size 0 or, if the file exists already, it is opened and
     * closed without modifying it, but updating the file date and time.
     * <p>
     * NOTE: As from v1.3, this method throws an IOException if the last
     * modified date of the file cannot be set. Also, as from v1.3 this method
     * creates parent directories if they do not exist.
     *
     * @param file  the File to touch
     * @throws IOException If an I/O problem occurs
     */
    public static void touch(File file) throws IOException {
        if (!file.exists()) {
            OutputStream out = openOutputStream(file);
            IOUtils.closeQuietly(out);
        }
        boolean success = file.setLastModified(System.currentTimeMillis());
        if (!success) {
            throw new IOException("Unable to set the last modification time for " + file);
        }
    }
    
    /**
     * Copies a file to a new location preserving the file date.
     * <p>
     * This method copies the contents of the specified source file to the
     * specified destination file. The directory holding the destination file is
     * created if it does not exist. If the destination file exists, then this
     * method will overwrite it.
     * <p>
     * <strong>Note:</strong> This method tries to preserve the file's last
     * modified date/times using {@link File#setLastModified(long)}, however
     * it is not guaranteed that the operation will succeed.
     * If the modification operation fails, no indication is provided.
     * 
     * @param srcFile  an existing file to copy, must not be {@code null}
     * @param destFile  the new file, must not be {@code null}
     * 
     * @throws NullPointerException if source or destination is {@code null}
     * @throws IOException if source or destination is invalid
     * @throws IOException if an IO error occurs during copying
     * @see #copyFileToDirectory(File, File)
     */
    public static void copyFile(File srcFile, File destFile) throws IOException {
        copyFile(srcFile, destFile, true);
    }
    
    /**
     * Copies a file to a new location.
     * <p>
     * This method copies the contents of the specified source file
     * to the specified destination file.
     * The directory holding the destination file is created if it does not exist.
     * If the destination file exists, then this method will overwrite it.
     * <p>
     * <strong>Note:</strong> Setting <code>preserveFileDate</code> to
     * {@code true} tries to preserve the file's last modified
     * date/times using {@link File#setLastModified(long)}, however it is
     * not guaranteed that the operation will succeed.
     * If the modification operation fails, no indication is provided.
     *
     * @param srcFile  an existing file to copy, must not be {@code null}
     * @param destFile  the new file, must not be {@code null}
     * @param preserveFileDate  true if the file date of the copy
     *  should be the same as the original
     *
     * @throws NullPointerException if source or destination is {@code null}
     * @throws IOException if source or destination is invalid
     * @throws IOException if an IO error occurs during copying
     * @see #copyFileToDirectory(File, File, boolean)
     */
    public static void copyFile(File srcFile, File destFile,
            boolean preserveFileDate) throws IOException {
        if (srcFile == null) {
            throw new NullPointerException("Source must not be null");
        }
        if (destFile == null) {
            throw new NullPointerException("Destination must not be null");
        }
        if (srcFile.exists() == false) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        }
        if (srcFile.isDirectory()) {
            throw new IOException("Source '" + srcFile + "' exists but is a directory");
        }
        if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
            throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
        }
        File parentFile = destFile.getParentFile();
        if (parentFile != null) {
            if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
                throw new IOException("Destination '" + parentFile + "' directory cannot be created");
            }
        }
        if (destFile.exists() && destFile.canWrite() == false) {
            throw new IOException("Destination '" + destFile + "' exists but is read-only");
        }
        doCopyFile(srcFile, destFile, preserveFileDate);
    }
    
    /**
     * Internal copy file method.
     * 
     * @param srcFile  the validated source file, must not be {@code null}
     * @param destFile  the validated destination file, must not be {@code null}
     * @param preserveFileDate  whether to preserve the file date
     * @throws IOException if an error occurs
     */
    private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            input  = fis.getChannel();
            output = fos.getChannel();
            long size = input.size();
            long pos = 0;
            long count = 0;
            while (pos < size) {
                count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
                pos += output.transferFrom(input, pos, count);
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(fis);
        }

        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" +
                    srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }
	
	public static void main(String args[]) throws Exception{
		//System.setProperty("file.encoding","UTF-8");
		System.out.println(System.getProperty("file.encoding"));
		System.out.println("1:"+fileToString(new File("C:\\weather\\101210101.shtml"),"UTF-8"));
		//System.out.println("2:"+fileToString(new File("C:\\weather\\101210101.shtml")));
		//moveFile(new File("C:\\Users\\e557400\\Desktop\\all\\newdoc\\Investigate\\java\\commons\\TimeZone.txt"),"C:\\");
		//moveFile(new File("C:\\TimeZone.txt"),"C:\\Users\\e557400\\Desktop\\all\\newdoc\\Investigate\\java\\commons");
//		System.out.println(getTempDirectoryPath());
//		File file = new File("C:\\Users\\e557400\\Desktop\\all\\newdoc\\Investigate\\java\\commons\\TimeZone.txt");
//		long size = file.length();
//		System.out.println(byteCountToDisplaySize(size));
	}
}

猜你喜欢

转载自a123159521.iteye.com/blog/2201822