`

文件工具类FileUtil.

 
阅读更多

/*
 * FileUtil.java
 * Copyright (C) 2007-3-19  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package org.lambdasoft.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
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;

/**
 * 文件工具类
 * 
 * 
@author TangLei <justinlei@gmail.com>
 * @date 2009-2-24
 
*/
public class FileUtil {
    
private static Log log = LogFactory.getLog(FileUtil.class);
    
private FileUtil() {}
    
    
/**
     * 获取随机的文件名称
     * 
@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 EncryptUtils.getMD5ofStr(seed).toLowerCase();
    }
    
    
/**
     * 列出所有当前层的文件和目录
     * 
     * 
@param dir            目录名称
     * 
@return fileList    列出的文件和目录
     
*/
    
public static File[] ls(String dir) {
        
return new File(dir).listFiles();
    }
    
    
/**
     * 根据需要创建文件夹
     * 
     * 
@param dirPath 文件夹路径
     * 
@param del    存在文件夹是否删除
     
*/
    
public static void mkdir(String dirPath,boolean del) {
        File dir 
= new File(dirPath);
        
if(dir.exists()) {
            
if(del)
                dir.delete();
            
else return;
        }
        dir.mkdirs();
    }
    
    
/**
     * 删除文件和目录
     * 
     * 
@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()) {
            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();
    }
    
    
/**
     * 把属性文件转换成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;
        }
    }
}

分享到:
评论

相关推荐

    FileUtil(文件操作工具类)

    FileUtil(文件操作工具类)

    Java文件处理工具类--FileUtil

    * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from ...

    java工具类:文件操作工具类.java

    protected static Logger log = LoggerFactory.getLogger(FileUtil.class); /** * 压缩文件 * @param inputFileName 要压缩的文件或文件夹路径,例如:c:\\a.txt,c:\\a\ * @param outputFileName 输出...

    java文件工具类FileUtil

    java文件工具类FileUtil 递归获取一个文件夹(及其子文件夹)下所有文件 获取扩展名 (doc/docx/jpg等) 判断是否是图片 判断是否是压缩包 是否是word文档 是否是excel

    FileUtil.java

    该工具类专门转对于Java中的数据文件的移动,复制,拷贝等方法,为开发者提供一系列的便捷的操作方法!极大的方便开发者开发!!

    FileUtil工具类

    文件上传的工具类。里面包括一些文件的下载以及上传。都是封装好的一些方法,很好用的。

    30个java工具类

    [工具类] 文件FileUtil.java [工具类] 通信客户端simpleClient.java [工具类] 通信服务端simpleServer.java [工具类] 框架StringUtil.java [工具类] 时间Time.java [工具类] 时间工具TimeUtil.java [工具类] 连...

    值得分享的超全文件工具类FileUtil

    主要为大家详细介绍了超全的文件工具类FileUtil,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    【强2】30个java工具类

    [工具类] 文件FileUtil.java [工具类] 通信客户端simpleClient.java [工具类] 通信服务端simpleServer.java [工具类] 框架StringUtil.java [工具类] 时间Time.java [工具类] 时间工具TimeUtil.java [工具类] 连...

    关于文件操作的工具类 -- FileUtil

    public class FileUtil { /** * 新建目录 * @param folderPath String 如 c:/fqf * @return boolean */ public static void newFolder(String folderPath) { try { String filePath = folderPath; ...

    FileUtil.rar

    最全文件操作工具类(包含文件大小转换、文件上传、下载、文件夹下载、解压、文件复制、文件夹复制、删除文件或文件夹等方法)

    fileutil工具类 处理文件流工具

    fileutil工具类 处理文件流工具 private static File file; /** * 判断文件是否存在 * * @param path * 文件路径 * @return boolean */ public static boolean fileIsExists(String path) { if (path ==...

    Android开发中的文件操作工具类FileUtil完整实例

    主要介绍了Android开发中的文件操作工具类FileUtil,结合完整实例形式分析了Android文件操作的常用技巧,包括文件的获取、遍历、搜索、复制、删除、判断等功能,需要的朋友可以参考下

    Java中各种工具类代码,.java文件以及使用说明

    包含各种工具类文件如ChangePinYin.java、CollectionUtil.java、DateUtil.java、DBConnectionUtil.java、FileUtil.java、FtpUtil.java、HttpClientUtil.java、MathUtil.java、MD5Util.java、StringUtil.java、...

    CreateFileUtil 创建文件工具类

    创建文件工具类 包含创建文件夹 文件 临时文件等

Global site tag (gtag.js) - Google Analytics