资料的相关操作 转转转

文件的相关操作 转转转
package com.Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class FileUtils   {
    private static Log log = LogFactory.getLog(FileUtils.class);
    private FileUtils() {}
   
    /**
     * 获取随机的文件名称
     * @param seed    随机种子
     * @return
     */
    public static String getRandomFileName(String seed) {
        byte[] ra = new byte[100];
        new Random().nextBytes(ra);
        StringBuilder build = new StringBuilder("");
        for (int i = 0; i < ra.length; i++) {
            build.append(Byte.valueOf(ra[i]).toString());
        }
        String currentDate = Long.valueOf(new Date().getTime()).toString();
        seed = seed + currentDate + build.toString();
        return MD5.encode((seed).toLowerCase());
    }
   
    /**
     * 列出所有当前层的文件和目录
     *
     * @param dir            目录名称
     * @return fileList    列出的文件和目录
     */
    public static File[] ls(String dir) {
        return new File(dir).listFiles();
    }
   
    /**
     * 根据需要创建文件夹
     *
     * @param dirPath 文件夹路径
     * @param del    存在文件夹是否删除  false 不创建文件夹..
     */
    public static boolean mkdir(String dirPath,boolean del) {
    boolean rs = false;
        File dir = new File(dirPath);
        //判断文件夹是否存在..
        if(dir.exists()) {
            if(del){
                dir.delete();
            }else{
            return false;
            }
        }
        dir.mkdirs();
        return true;
    }
   
    /**
     * 删除文件和目录
     *
     * @param path
     * @throws Exception
     */
    public static void rm(String path) throws Exception{
        if(log.isDebugEnabled())
            log.debug("需要删除的文件: " + path);
        File file = new File(path);
       
        //判断文件是否存在,,不存在不用删除
        if(!file.exists()) {
            if(log.isWarnEnabled())
                log.warn("文件<" + path + ">不存在");
            return;
        }
        //判断这个文件是否是一个文件夹..
        if(file.isDirectory()) {
        //是一个文件夹....
        //listFiles()把所有文件夹下内容列..
            File[] fileList = file.listFiles();
            if(fileList == null || fileList.length == 0) {
            //如果文件夹空,直接删除..
                file.delete();
            } else {
            //如果文件夹不空,把内容一个一个取出来,迭归判断...
            //自己调用自己迭归..
                for (File _file : fileList) {
                //把文件 内容绝对地址
                    rm(_file.getAbsolutePath());
                }
            }
        file.delete();
        } else {
        //如果你删除的是一个文件..
            file.delete();
        }
    }
   
    /**
     * 移动文件
     *
     * @param source     源文件
     * @param target         目标文件
     * @param cache        文件缓存大小
     * @throws Exception
     */
    public static void mv(String source,String target,int cache) throws Exception {
        if(source.trim().equals(target.trim()))
            return;
        byte[] cached = new byte[cache];
        FileInputStream fromFile = new FileInputStream(source);
        FileOutputStream toFile = new FileOutputStream(target);
        while(fromFile.read(cached) != -1) {
            toFile.write(cached);
        }
        toFile.flush();
        toFile.close();
        fromFile.close();
        new File(source).deleteOnExit();
    }
   
    /**
     * 文件复制
     * @param source
     * @param target
     */
    public static void cp(String source,String target){
    FileInputStream fin = null;
    FileOutputStream fout = null;
    //提升性能用一个数组;
    byte[] cache = new byte[1024 * 8];
    try {
fin = new FileInputStream(source);
fout = new FileOutputStream(target);
int size = fin.read(cache);
while(size != -1){
fout.write(cache, 0, size);
size = fin.read(cache);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fout != null){
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fin != null){
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
    }
    /**
     * 把属性文件转换成Map
     *
     * @param propertiesFile
     * @return
     * @throws Exception
     */
    public static final Map<String, String> getPropertiesMap(String propertiesFile) throws Exception{
        Properties properties = new Properties();
        FileInputStream inputStream = new FileInputStream(propertiesFile);
        properties.load(inputStream);
        Map<String, String> map = new HashMap<String, String>();
        Set<Object> keySet = properties.keySet();
        for (Object key : keySet) {
            map.put((String)key, properties.getProperty((String)key));
        }
        return map;
    }
   
    @SuppressWarnings("unchecked")
    public static final Map<String, String> getPropertiesMap(Class clazz,String fileName) throws Exception{
        Properties properties = new Properties();
        InputStream inputStream = clazz.getResourceAsStream(fileName);
        if(inputStream == null)
            inputStream = clazz.getClassLoader().getResourceAsStream(fileName);
        properties.load(inputStream);
        Map<String, String> map = new HashMap<String, String>();
        Set<Object> keySet = properties.keySet();
        for (Object key : keySet) {
            map.put((String)key, properties.getProperty((String)key));
        }
        return map;
    }
   
    /**
     * 把属性文件转换成Map
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static final Map<String, String> getPropertiesMap(InputStream inputStream) throws Exception{
        Properties properties = new Properties();
        properties.load(inputStream);
        Map<String, String> map = new HashMap<String, String>();
        Set<Object> keySet = properties.keySet();
        for (Object key : keySet) {
            map.put((String)key, properties.getProperty((String)key));
        }
        return map;
    }
   
    /**
     * 把文本文件转换成String
     *
     * @param fullPath
     * @return
     * @throws Exception
     */
    public static String readFile(String fullPath) throws Exception{
        BufferedReader reader = new BufferedReader(new FileReader(fullPath));
        if(reader == null)
            return null;
        StringBuilder builder = new StringBuilder("");
        String line = null;
        while((line = reader.readLine()) != null) {
            builder.append(line + "\n");
        }
        return builder.toString();
    }
   
    /**
     * 获取资源文件流
     *
     * @param clazz
     * @param name
     * @return
     */
    @SuppressWarnings("unchecked")
    public static InputStream getResourceAsStream(Class clazz,String name) {
        try {
            InputStream inputStream = clazz.getResourceAsStream(name);
            if(inputStream == null)
                inputStream = clazz.getClassLoader().getResourceAsStream(name);
            return inputStream;
        } catch (Exception e) {
            if(log.isWarnEnabled())
                log.warn("获取资源文件失败", e);
            return null;
        }
    }
   
    /**
     * 文件重命名
     * @param path
     * @param oldname
     * @param newname
     */
    public static void renameFile(String path,String oldname,String newname){ 
             if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名 
                 File oldfile=new File(path+"/"+oldname); 
                 File newfile=new File(path+"/"+newname); 
                 if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名 
                     System.out.println(newname+"已经存在!"); 
                 else{ 
                     oldfile.renameTo(newfile); 
                 } 
             } 
    }            
//            
    public static void main(String[] args){
//    File [] lists = ls(".");
//    for(File f:lists){
//    System.out.println(f.getName());
//    }
    //boolean is = mkdir("a",false);
    //System.out.println(is);
//    try{
//    rm("a");
//    }catch(Exception e){
//    e.printStackTrace();
//    }
//    try{
//    long start = System.currentTimeMillis();
//    mv("f://AdbeRdr920_zh_CN.exe","e://c.exe",1024 *资料的相关操作   转转转;
//    long end = System.currentTimeMillis();
//    System.out.println(end - start);
//    }catch(Exception e){
//    e.printStackTrace();
//    }
    }