`

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));
	}
}

分享到:
评论

相关推荐

    commons-io-2.2-API文档-中文版.zip

    赠送jar包:commons-io-2.2.jar; 赠送原API文档:commons-io-2.2-javadoc.jar; 赠送源代码:commons-io-2.2-sources.jar; 包含翻译后的API文档:commons-io-2.2-javadoc-API文档-中文(简体)版.zip 对应Maven...

    commons-io-2.5-API文档-中文版.zip

    赠送jar包:commons-io-2.5.jar; 赠送原API文档:commons-io-2.5-javadoc.jar; 赠送源代码:commons-io-2.5-sources.jar; 赠送Maven依赖信息文件:commons-io-2.5.pom; 包含翻译后的API文档:commons-io-2.5-...

    commons-io-1.3.2-API文档-中文版.zip

    赠送jar包:commons-io-1.3.2.jar; 赠送原API文档:commons-io-1.3.2-javadoc.jar; 赠送源代码:commons-io-1.3.2-sources.jar; 赠送Maven依赖信息文件:commons-io-1.3.2.pom; 包含翻译后的API文档:commons-io...

    commons-io-2.11.0-API文档-中文版.zip

    赠送jar包:commons-io-2.11.0.jar; 赠送原API文档:commons-io-2.11.0-javadoc.jar; 赠送源代码:commons-io-2.11.0-sources.jar; 赠送Maven依赖信息文件:commons-io-2.11.0.pom; 包含翻译后的API文档:...

    commons-io-2.7-API文档-中文版.zip

    赠送jar包:commons-io-2.7.jar; 赠送原API文档:commons-io-2.7-javadoc.jar; 赠送源代码:commons-io-2.7-sources.jar; 赠送Maven依赖信息文件:commons-io-2.7.pom; 包含翻译后的API文档:commons-io-2.7-...

    commons-io-2.7-API文档-中英对照版.zip

    赠送jar包:commons-io-2.7.jar 赠送原API文档:commons-io-2.7-javadoc.jar 赠送源代码:commons-io-2.7-sources.jar 包含翻译后的API文档:commons-io-2.7-javadoc-API文档-中文(简体)-英语-对照版.zip 对应...

    commons-io-2.8.0-API文档-中英对照版.zip

    赠送jar包:commons-io-2.8.0.jar; 赠送原API文档:commons-io-2.8.0-javadoc.jar; 赠送源代码:commons-io-2.8.0-sources.jar; 赠送Maven依赖信息文件:commons-io-2.8.0.pom; 包含翻译后的API文档:commons-io...

    commons-io-2.11.0-API文档-中英对照版.zip

    赠送jar包:commons-io-2.11.0.jar; 赠送原API文档:commons-io-2.11.0-javadoc.jar; 赠送源代码:commons-io-2.11.0-sources.jar; 赠送Maven依赖信息文件:commons-io-2.11.0.pom; 包含翻译后的API文档:...

    开发工具 commons-io-1.3.2

    开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2开发工具 commons-io-1.3.2...

    commons-fileupload-1.3.3.jar和commons-io-2.6.jar

    在Java开发中,上传文件是一项常见的任务,而`commons-fileupload-1.3.3.jar`和`commons-io-2.6.jar`是Apache Commons项目中的两个重要库,专门用于处理HTTP请求中的文件上传功能。这两个库为开发者提供了便捷、高效...

    commons-io-2.8.0-API文档-中文版.zip

    赠送jar包:commons-io-2.8.0.jar; 赠送原API文档:commons-io-2.8.0-javadoc.jar; 赠送源代码:commons-io-2.8.0-sources.jar; 赠送Maven依赖信息文件:commons-io-2.8.0.pom; 包含翻译后的API文档:commons-io...

    commons-io-2.4 包含了所有commons-io的jar包和源码

    在本案例中,我们讨论的是"commons-io-2.4"版本,这个版本包含了完整的Apache Commons IO库的jar包和源代码,适用于JDK 1.6及以上版本。 Apache Commons IO 提供了许多实用工具类,使得开发者在处理输入/输出操作时...

    java-IO流 commons-io-2.11.0.jar

    java-IO流 commons-io-2.11.0.jar

    Java IO commons-io-2.5.jar

    相较于Java标准库中的`java.io.File`类提供的`copy()`方法,`commons-io`的`FileUtils.copyFile()`更简单易用,且异常处理更简洁。 总的来说,`commons-io-2.5.jar` 是Java开发者的强大工具,它极大地扩展了Java IO...

    commons-fileupload-1.2.1.jar与commons-io-1.3.2.jar

    其次,`commons-io-1.3.2.jar`是Apache Commons IO库的一部分,这是一个通用的IO(Input/Output)操作工具集,为Java开发者提供了大量实用的IO操作方法。在处理文件上传时,`commons-fileupload`可能会依赖`commons-...

    commons-io-2.0.1大全

    Commons IO是apache的一个开源的工具包,封装了IO操作的相关类,包含了最新的commons-io-2.0.1-bin,commons-io-2.0.1-src,commons-io-2.0.1-doc

    commons-io-2.4.jar包 官方免费版

    标题提到的"commons-io-2.4.jar"是这个库的一个版本,版本号为2.4,表明它是官方发布的稳定版本,对先前版本进行了优化和改进。 `commons-io`库包含了许多类和方法,主要集中在以下几个方面: 1. **文件操作**:...

    commons-io-2.5.jar

    commons-io-2.5 &lt;groupId&gt;org.apache.commons &lt;artifactId&gt;commons-parent &lt;version&gt;39 &lt;modelVersion&gt;4.0.0 &lt;groupId&gt;commons-io &lt;artifactId&gt;commons-io &lt;version&gt;2.5 &lt;name&gt;Apache Commons IO&lt;/name&gt;

    commons-fileupload.jar和commons-io.jar

    然后在Controller中,可以直接通过`@RequestParam("file") MultipartFile file`来接收上传的文件,这里MultipartFile就是由`commons-fileupload`和`commons-io`支持的。 对于MyBatis,虽然它主要关注数据库操作,但...

    commons-io-1.4.jar.zip_io流jar

    《Java IO流详解与commons-io-1.4.jar库的应用》 在Java编程语言中,IO(Input/Output)流是一组用于数据传输的类,它们允许程序读取和写入数据,无论是从磁盘、网络还是其他输入输出设备。Java的IO流系统是一个...

Global site tag (gtag.js) - Google Analytics