java操作文件工具类

package org.jboss.tools.esb.project.ui.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;



/**
 * @author Grid Qian
 */
public class UIUtils
{
    /**
     * A default padding value for horizontalResize().
     */
    public final static int DEFAULT_PADDING = 35;

    String infoPopid_;

    public UIUtils(String infoPopid)
    {
        infoPopid_ = infoPopid;
    }

   

    public static void writePropertyToFile(File file, String key, String value) throws IOException
    {
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "8859_1"));
        out.write(key + "=" + value + "\n");
        out.close();
    }

    // file util
    public static void copyFile(String src, String dest)
    {
        InputStream is = null;
        FileOutputStream fos = null;

        try
        {
            is = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            int c = 0;
            byte[] array = new byte[1024];
            while ((c = is.read(array)) >= 0)
            {
                fos.write(array, 0, c);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                fos.close();
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static File createFileAndParentDirectories(String fileName) throws Exception
    {
        File file = new File(fileName);
        File parent = file.getParentFile();
        if (!parent.exists())
        {
            parent.mkdirs();
        }
        file.createNewFile();
        return file;
    }
    /**删除文件*/
	
    public static boolean deleteDir(File dir)
    {
        if (dir.isDirectory())
        {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++)
            {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success)
                {
                    return false;
                }
            }
        }
        return dir.delete();
    }
/***删除文件目录*/
    public static void deleteDirectories(File dir)
    {
        File[] children = dir.listFiles();
        for (int i = 0; i < children.length; i++)
        {
            if (children[i].list() != null && children[i].list().length > 0)
            {
                deleteDirectories(children[i]);
            }
            else
            {
                children[i].delete();
            }
        }
        dir.delete();
    }

/***删除文件目录*/
    public static void deleteDirectories(String dir)
    {
        File directory = new File(dir);
        deleteDirectories(directory);
    }
/***创建文件*/
    public static void createTargetFile(String sourceFileName, String targetFileName) throws Exception
    {
        createTargetFile(sourceFileName, targetFileName, false);
    }

/***创建文件是否覆盖*/
    public static void createTargetFile(String sourceFileName, String targetFileName, boolean overwrite)
            throws Exception
    {
        File idealResultFile = new File(targetFileName);
        if (overwrite || !idealResultFile.exists())
        {
            createFileAndParentDirectories(targetFileName);
            copyFile(sourceFileName, targetFileName);
        }
    }

/***创建文件目录*/
    public static boolean createDirectory(String directory)
    {
        // Create a directory; all ancestor directories must exist
        boolean success = (new File(directory)).mkdir();
        if (!success)
        {
            // Directory creation failed
        }
        return success;
    }

/***创建文件目录*/
    public static boolean createDirectorys(String directory)
    {
        // Create a directory; all ancestor directories must exist
        boolean success = (new File(directory)).mkdirs();
        if (!success)
        {
            // Directory creation failed
        }
        return success;
    }

    // Copies all files under srcDir to dstDir.
    // If dstDir does not exist, it will be created.
/**复制文件目录*/
    public static void copyDirectory(File srcDir, File dstDir) throws IOException
    {
        if (srcDir.isDirectory())
        {
            if (!dstDir.exists())
            {
                dstDir.mkdir();
            }

            String[] children = srcDir.list();
            for (int i = 0; i < children.length; i++)
            {
                copyDirectory(new File(srcDir, children[i]), new File(dstDir, children[i]));
            }
        }
        else
        {
            copy(srcDir, dstDir);
        }
    }

    // Copies src file to dst file.
    // If the dst file does not exist, it is created
/**复制文件*/
    public static void copy(File src, File dst) throws IOException
    {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
        {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

    public static String addAnotherNodeToPath(String currentPath, String newNode)
    {
        return currentPath + File.separator + newNode;
    }

    public static String addNodesToPath(String currentPath, String[] newNode)
    {
        String returnPath = currentPath;
        for (int i = 0; i < newNode.length; i++)
        {
            returnPath = returnPath + File.separator + newNode[i];
        }
        return returnPath;
    }

    public static String addNodesToPath(StringBuffer currentPath, String[] pathNodes)
    {
        for (int i = 0; i < pathNodes.length; i++)
        {
            currentPath.append(File.separator);
            currentPath.append(pathNodes[i]);
        }
        return currentPath.toString();
    }

    public static String addNodesToURL(String currentPath, String[] newNode)
    {
        String returnPath = currentPath;
        for (int i = 0; i < newNode.length; i++)
        {
            returnPath = returnPath + "/" + newNode[i];
        }
        return returnPath;
    }

    /**
     * Get the list of file with a prefix of <code>fileNamePrefix</code> & an extension of <code>extension</code>
     * 
     * @param sourceDir The directory in which to search the files
     * @param fileNamePrefix The prefix to look for
     * @param extension The extension to look for
     * @return The list of file with a prefix of <code>fileNamePrefix</code> & an extension of
     *         <code>extension</code>
     */
    public static File[] getMatchingFiles(String sourceDir, String fileNamePrefix, String extension)
    {
        List<File> fileList = new ArrayList<File>();
        File libDir = new File(sourceDir);
        String libDirPath = libDir.getAbsolutePath();
        String[] items = libDir.list();
        if (items != null)
        {
            for (int i = 0; i < items.length; i++)
            {
                String item = items[i];
                if (fileNamePrefix != null && extension != null)
                {
                    if (item.startsWith(fileNamePrefix) && item.endsWith(extension))
                    {
                        fileList.add(new File(libDirPath + File.separator + item));
                    }
                }
                else if (fileNamePrefix == null && extension != null)
                {
                    if (item.endsWith(extension))
                    {
                        fileList.add(new File(libDirPath + File.separator + item));
                    }
                }
                else if (fileNamePrefix != null && extension == null)
                {
                    if (item.startsWith(fileNamePrefix))
                    {
                        fileList.add(new File(libDirPath + File.separator + item));
                    }
                }
                else
                {
                    fileList.add(new File(libDirPath + File.separator + item));
                }
            }
            return (File[]) fileList.toArray(new File[fileList.size()]);
        }
        return new File[0];
    }

    /**
     * Filter out files inside a <code>sourceDir</code> with matching <codefileNamePrefix></code> and
     * <code>extension</code>
     * 
     * @param sourceDir The directory to filter the files
     * @param fileNamePrefix The filtering filename prefix
     * @param extension The filtering file extension
     */
    public static void filterOutRestrictedFiles(String sourceDir, String fileNamePrefix, String extension)
    {
        File[] resultedMatchingFiles = getMatchingFiles(sourceDir, fileNamePrefix, extension);
        for (int i = 0; i < resultedMatchingFiles.length; i++)
        {
            File matchingFilePath = new File(resultedMatchingFiles[i].getAbsolutePath());
            matchingFilePath.delete();
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值