文件工具类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;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java 文件上传下载工具类的示例代码: ```java import java.io.*; import java.net.URL; import java.net.URLConnection; public class FileUtil { /** * 上传文件 * @param targetURL 目标 URL * @param file 要上传的文件 * @return 服务器返回的结果 */ public static String uploadFile(String targetURL, File file) { String response = null; try { URL url = new URL(targetURL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****"); OutputStream outputStream = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); String fileName = file.getName(); writer.append("--*****").append("\r\n"); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"").append("\r\n"); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append("\r\n"); writer.append("Content-Transfer-Encoding: binary").append("\r\n"); writer.append("\r\n"); writer.flush(); FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append("\r\n"); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response = line; } writer.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } return response; } /** * 下载文件 * @param fileURL 文件 URL * @param saveDir 文件保存目录 * @return 下载后的文件 */ public static File downloadFile(String fileURL, String saveDir) { File file = null; try { URL url = new URL(fileURL); URLConnection connection = url.openConnection(); connection.connect(); InputStream inputStream = connection.getInputStream(); String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1); file = new File(saveDir + File.separator + fileName); FileOutputStream outputStream = new FileOutputStream(file); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return file; } } ``` 使用示例: ```java // 上传文件 File file = new File("test.txt"); String response = FileUtil.uploadFile("http://example.com/upload.php", file); System.out.println("服务器返回:" + response); // 下载文件 File downloadedFile = FileUtil.downloadFile("http://example.com/download.php?id=123", "downloads"); System.out.println("下载的文件位置:" + downloadedFile.getAbsolutePath()); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值