cn.fql.utility.FileUtility.java Source code

Java tutorial

Introduction

Here is the source code for cn.fql.utility.FileUtility.java

Source

/*
 * File: $RCSfile$
 *
 * Copyright (c) 2005 Wincor Nixdorf International GmbH,
 * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Wincor Nixdorf ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Wincor Nixdorf.
 */
package cn.fql.utility;

import org.apache.commons.lang.StringUtils;

import java.security.Permission;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

/**
 * The class <code>cn.fql.utility.FileUtility</code>
 *
 * @author User, WN ASP SSD
 * @version $Revision$
 */
public class FileUtility {
    public static final SecurityManager SECURITYMANAGER = new SecurityManager() {
        public void checkPermission(Permission perm) {
        }
    };
    public static final SecurityManager SYSSECURITYMANAGER = System.getSecurityManager();

    private FileUtility() {
    }

    /**
     * delete file with specified file name
     *
     * @param file file name
     * @return if delete success, return true, else return false
     */
    public static boolean deleteFile(String file) {
        System.setSecurityManager(SECURITYMANAGER);
        boolean isDeleted;
        File aFile = new File(file);
        if (aFile.exists() && aFile.isFile()) {
            isDeleted = aFile.delete();
        } else {
            isDeleted = false;
        }
        System.setSecurityManager(SYSSECURITYMANAGER);
        return isDeleted;
    }

    /**
     * write file with specified path and content
     *
     * @param filePath file path
     * @param content  file content
     */
    public static void writeFile(String filePath, byte[] content) {
        System.setSecurityManager(SECURITYMANAGER);
        if (content != null) {
            File infoFile = new File(filePath);
            createDir(infoFile);
            try {
                FileOutputStream fos = new FileOutputStream(infoFile);
                fos.write(content);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.setSecurityManager(SYSSECURITYMANAGER);
    }

    /**
     * write file with specified path and content
     *
     * @param infoFile file path
     * @param content  file content
     */
    public static void writeFile(File infoFile, byte[] content) {
        System.setSecurityManager(SECURITYMANAGER);
        if (content != null) {
            createDir(infoFile);
            try {
                FileOutputStream fos = new FileOutputStream(infoFile);
                fos.write(content);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.setSecurityManager(SYSSECURITYMANAGER);
    }

    /**
     * read file to byte[] with specified file path
     *
     * @param filePath specified file path
     * @return <code>byte[]</code> file content
     */
    public static byte[] readFile(String filePath) {
        File infoFile = new File(filePath);
        byte[] result = null;
        if (infoFile.exists()) {
            result = new byte[(int) infoFile.length()];
            try {
                FileInputStream fis = new FileInputStream(infoFile);
                fis.read(result);
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * make a directory for specified file
     * if directory existed, it is not requried to create a new one
     *
     * @param file specified file<code>java.io.File</code>
     */
    public static void createDir(File file) {
        if (!file.exists()) {
            File dir = file.getParentFile();
            if (dir != null && !dir.exists()) {
                dir.mkdirs();
            }
        }
    }

    /**
     * Copy sourceFolder's content to a new folder
     *
     * @param sourceFolder source folder
     * @param newfolder    destinate folder
     */
    public static void copyFolder(String sourceFolder, String newfolder) {
        copyFolder(sourceFolder, newfolder, true);
    }

    /**
     * Copy source folder's content to a new folder, if there are existed duplicated files and overwrite
     * flag is true, it might overwrite it
     *
     * @param sourceFolder   source folder path
     * @param newFolder      new folder path
     * @param forceOverwrite determine whether it is required to overwrite for duplicated files
     */
    public static void copyFolder(String sourceFolder, String newFolder, boolean forceOverwrite) {
        String oldPath = StringUtils.replace(sourceFolder, "/", File.separator);
        String newPath = StringUtils.replace(newFolder, "/", File.separator);
        if (!oldPath.endsWith(File.separator)) {
            oldPath = oldPath + File.separator;
        }
        if (!newPath.endsWith(File.separator)) {
            newPath = newPath + File.separator;
        }
        new File(newPath).mkdirs();
        File sourceDir = new File(oldPath);
        String[] files = sourceDir.list();
        File oldFile;
        File newFile;
        for (int i = 0; i < files.length; i++) {
            oldFile = new File(oldPath + files[i]);
            newFile = new File(newPath + files[i]);
            if (oldFile.isFile() && (!forceOverwrite || (!newFile.exists() || oldFile.length() != newFile.length()
                    || oldFile.lastModified() > newFile.lastModified()))) {
                copyFile(oldFile.getPath(), newFile.getPath());
            }
            if (oldFile.isDirectory()) {
                copyFolder(oldPath + files[i], newPath + files[i], forceOverwrite);
            }
        }
    }

    /**
     * Copy file from source path to a new path
     *
     * @param sourcePath source path
     * @param newPath    new path
     */
    public static void copyFile(String sourcePath, String newPath) {
        byte[] sourceByte = readFile(sourcePath);
        writeFile(newPath, sourceByte);
        if (isExisted(newPath)) {
            System.out.println("Copy " + sourcePath + " to " + newPath + " successful!");
        } else {
            System.out.println("Copy " + sourcePath + " to " + newPath + " not successful!");
        }
    }

    /**
     * Return boolean value denotes whether the file with specified file path existed
     *
     * @param filePath File path
     * @return Boolean value denotes whether the file with specified file path existed
     */
    public static boolean isExisted(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * Copy file and remove the old one.
     *
     * @param sourcePath {@link #copyFile(String,String)}
     * @param newPath    {@link #copyFile(String,String)}
     */
    public static void cutFile(String sourcePath, String newPath) {
        copyFile(sourcePath, newPath);
        File file = new File(sourcePath);
        if (file.isDirectory()) {
            deleteAll(file);
        } else {
            deleteFile(sourcePath);
        }
    }

    /**
     * visit all a director and delete them in a list,write deleted files' name to list
     *
     * @param dir directory
     * @return deleted file name list
     */
    private static List deleteAll(File dir) {
        System.setSecurityManager(SECURITYMANAGER);
        List allFiles = new ArrayList();
        File[] dirs = dir.listFiles();
        if (dirs != null) {
            List dirsList = Arrays.asList(dirs);
            if (dirsList == null) {
                try {
                    dir.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                allFiles.addAll(dirsList);
                for (Iterator it = dirsList.iterator(); it.hasNext();) {
                    File _tempRoot = (java.io.File) it.next();
                    allFiles.addAll(deleteAll(_tempRoot));
                }
            }
        }
        System.setSecurityManager(SYSSECURITYMANAGER);
        return allFiles;
    }

    /**
     * do delete all files under specified file's dir
     *
     * @param root specified file root
     */
    public static void deleteDirs(File root) throws Exception {
        System.setSecurityManager(SECURITYMANAGER);
        if (root.isDirectory()) {
            List allFiles = deleteAll(root);
            if (allFiles != null) {
                for (int i = allFiles.size() - 1; i >= 0; i--) {
                    java.io.File f = (java.io.File) allFiles.remove(i);
                    String fileName = f.toString();
                    if (!f.delete()) {
                        throw new Exception("Exception: delete file " + fileName + " false!");
                    }
                }
            }
        }
        System.setSecurityManager(SYSSECURITYMANAGER);
    }

    /**
     * return input  stream from specified url
     *
     * @param url specified url
     * @return <code>java.io.InputStream</code>
     */
    public static InputStream getInputStream(String url) {
        InputStream is = null;
        if (url != null) {
            if (url.indexOf(File.separator) != -1) {
                byte[] infoArray = readFile(url);
                if (infoArray != null) {
                    is = new ByteArrayInputStream(infoArray);
                }
            } else {
                is = Thread.currentThread().getContextClassLoader().getResourceAsStream(url);
            }
        }
        return is;
    }

    /**
     * Return last modified time of specified file
     *
     * @param fileName file name
     * @return last modified time long value
     */
    public static long getLastModifiedTime(String fileName) {
        try {
            java.io.File f = new java.io.File(fileName);
            return f.lastModified();
        } catch (Exception ex) {
            return -1;
        }
    }

    /**
     * Return extension file name with specified file name
     *
     * @param fileName File name
     * @return Extension file name
     */
    public static String getExtFileName(String fileName) {
        String extFileName;
        char[] fileCharArray = fileName.toCharArray();
        int breakIndex = fileCharArray.length - 1;
        for (; breakIndex > 0; breakIndex--) {
            if (fileCharArray[breakIndex] == '.') {
                break;
            }
        }
        extFileName = fileName.substring(breakIndex + 1, fileCharArray.length);
        return extFileName;
    }
}
/**
 * History:
 *
 * $Log$
 */