文件工具類

package com.tkb.daboweb.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ssh.spring.DeployInfoUtil;
import app.j2ee.data.RandKeyCreator;
import app.j2ee.file.FileUtil;
import app.other.commons.file.MutiFileUpload;
import app.other.poi.excel.ExcelUtil;

public class FileTempUtil {
	
	private static final Log log = LogFactory.getLog(FileTempUtil.class);
	
	
	
	public static String getParam(String param, Map map){
		String temp = "";
		if(map != null){
			Object o =  map.get(param);
			if (o != null) {
				temp = (String)o;
				try {
					temp = new String(temp.getBytes("iso-8859-1"), "utf8");
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		return temp.trim();
	}
	//接收Integer
	public static Integer getIntParam(String param, Map map,Integer defaultValue){
		int num = defaultValue;
		if(map != null){
			Object o =  map.get(param);
			if (o != null) {
				try {
					o = new String(((String)o).getBytes("iso-8859-1"), "utf8");
					num = Integer.parseInt((String)o);
				} catch (Exception e) {
				}
			}
		}
		return num;
		
	}
	
	//接收Date yyyy-MM-dd
	public static Date getDateParam(String param, Map map){
		 String temp = getParam(param, map);
		 Date date = null;
		 if(!temp.equals("")){
			 date = DataFormater.getDate(temp + " 00:00:00", DataFormater.DATATIME_STR); 
		 }
		 return date;
	}
	
	 
	
	
	/**
	 * 取得普通表單數據
	 * @param request
	 * @return
	 */
	public static Map getPreParameters(MutiFileUpload upload){
		return upload.parameters;
	}
	
	/**
	 * 多文件上傳 
	 * 返回 上傳文件路徑 及 原始檔案名
	 * 
	 * folder 文件夹
	 * id 文件夹
	 * isRandom,是否用随机数
	 * 
	 * return map
	 * key-oldXXX(原文件名), newXXX(新文件名), XXX(虚拟文件名)
	 */
	
	public static Map<String,String> upload(MutiFileUpload upload, String folder, String id, boolean isRandom) throws Exception {
		Map<String,String> temp = new HashMap<String,String>();
		
		String rootPath = DeployInfoUtil.getUploadFilePath() + ConstantsUtil.UPLOADFILE_PATH + File.separator +
		folder + File.separator;
		
		String virtualPath = ConstantsUtil.UPLOADFILE_PATH + File.separator +folder + File.separator;
		
		Iterator iterator = upload.files.values().iterator();
		while (iterator.hasNext()) {
			FileItem item = (FileItem) iterator.next();
			if (upload.getFileName(item) == null
					|| upload.getFileName(item).equals(""))
				continue;
			String rankKey = RandKeyCreator.getRandStr(12);
			String fileName = upload.getFileName(item); //原來的檔案名
			String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length());
			String fieldName = item.getFieldName();
			//設置原始檔案名
			temp.put("old"+fieldName, fileName); //原始文件名称 abc.jpg
		    if(isRandom){
		    	fileName = rankKey+fileType;
		    }
		    temp.put("new" + fieldName, fileName); //随机文件名 3434343434a.jpg
			FileUtil.saveFile(rootPath + id + File.separator ,fileName, item.get());
			fileName = virtualPath + id + File.separator + fileName;
			temp.put(fieldName, fileName.replace("\\", "/"));	//url文件名 upload/news/1/3434343434a.jpg
		}
		
		return temp;
	}
	
	
	
	
	/**
	 * 多文件上傳 
	 * @param request
	 * @param folder 資源文件 如,game
	 * @param id 表中id
	 * @param files	game下面二級目錄如game、pic 若沒有則null
	 * @return
	 * @throws Exception
	 */
	
	public static Map<String,String> upload(MutiFileUpload upload, String folder, String id, String [] files) throws Exception {
		Map<String,String> temp = new HashMap<String,String>();
		
		String rootPath = DeployInfoUtil.getUploadFilePath() + ConstantsUtil.UPLOADFILE_PATH + File.separator +
		folder + File.separator;
		
		String virtualPath = ConstantsUtil.UPLOADFILE_PATH + File.separator +folder + File.separator;
		
		Iterator iterator = upload.files.values().iterator();
		while (iterator.hasNext()) {
			FileItem item = (FileItem) iterator.next();
			if (upload.getFileName(item) == null
					|| upload.getFileName(item).equals(""))
				continue;
			String rankKey = RandKeyCreator.getRandStr(12);
			String fileName = upload.getFileName(item); //原來的檔案名			
			String fieldName = item.getFieldName();
			if(files == null){
				FileUtil.saveFile(rootPath + id + File.separator + rankKey,fileName, item.get());
				fileName = virtualPath + id + File.separator + rankKey + File.separator + fileName;
				temp.put(fieldName, fileName.replace("\\", "/"));
			}else{
				for(String file:files){
					if(file.equals(fieldName)){
						FileUtil.saveFile(rootPath + file + File.separator + id + File.separator + rankKey,
								fileName, item.get());
						fileName = virtualPath + file + File.separator + id + File.separator + rankKey + File.separator + fileName;
						temp.put(fieldName, fileName.replace("\\", "/"));
						break;
					}
				}
			}
		}
		
		return temp;
	}
	
	public static void delFile(String fileName) throws Exception{
		String filePath = fileName.substring(0,fileName.lastIndexOf("/"));
		filePath = fileName.substring(0,filePath.lastIndexOf("/"));
		filePath = DeployInfoUtil.getUploadFilePath() + filePath.replace("/", "\\");
		FileUtil.delAll(new File(filePath));
	}
	
	public static void delUpdateFile(String fileName) throws Exception{
		String filePath = fileName.substring(0,fileName.lastIndexOf("/"));
		filePath = DeployInfoUtil.getUploadFilePath() + filePath.replace("/", "\\");
		FileUtil.delAll(new File(filePath));
	}
	//add by zhangmingshuang ---------2012-02-21
	public static void delFilePost(String fileName) throws Exception{
		String filePath = fileName.substring(0,fileName.lastIndexOf("/"));
		filePath = DeployInfoUtil.getUploadFilePath() + filePath.replace("/", "\\");
		FileUtil.delAll(new File(filePath));
	}
	public static void delUpdateFilePost(String fileName) throws Exception{
		String filePath = DeployInfoUtil.getUploadFilePath() + fileName.replace("/", "\\");
		FileUtil.delAll(new File(filePath));
	}

	/**
	 * 文件長度單位處理
	 * @param orilength
	 * @return
	 */
	public static  String getFileSizeHandle(long orilength){
		DecimalFormat df = new DecimalFormat( "0.## "); 
		if(orilength < 1024){
			return orilength+"B";
		}else if(orilength < 1024*1024){
			Float si=orilength/1024f;
			return df.format(si)+"KB";
		}else{
			Float si=orilength/1024f/1024f;
			return df.format(si)+"M";
		}
		
		
	}
	
	
	
	
	
	
	/**
	 * 下載
	 * @param request
	 * @param response
	 * @param path 路径Z:\huayuschool\
	 * @param fileName 文件名 
	 * @throws Exception
	 * @return loadFlag ---true 下載成功, false  下載失敗
	 */
	public static boolean download(HttpServletRequest request, HttpServletResponse response, String path, String fileName) throws Exception{  
		boolean loadFlag = true; //下載成功標志位
		File file = null;
		InputStream in = null; // 輸入流
		OutputStream out = null; // 輸出流
		//在下載附件之前設置響應類型和頭部文件
		response.setContentType("application/x-msdownload");
		response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(ExcelUtil.subLastStr(fileName, "/"),"UTF-8"));		
		try{
			file = new File(path); //取得文件對像
            //從下載附件創建輸入流,并向請求獲取并寫入(客戶端或網絡)輸出流
			in = new BufferedInputStream(new FileInputStream(file));
			out = response.getOutputStream();
			int readSize = 1024 * 10; //讀取大小
			int length = 0; //讀取剩余大小
			byte[] readByte = new byte[readSize];
			while ((length = in.read(readByte, 0, readSize)) != -1) {
				out.write(readByte, 0, length);
			}
			out.flush();
		}catch(Exception e){
			loadFlag = false;
			e.printStackTrace();
		}finally{
			if(in!=null || out!=null ){
				try {
					in.close();
					out.close();
				} catch (IOException e) {
					loadFlag = false;
					e.printStackTrace();
				}	
			}
		}
		return loadFlag;
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
Apache文件工具类是Apache Commons Lang3工具包中的一个类,提供了一系列用于文件操作的方法,例如读取文件、写入文件、复制文件、删除文件等。这些方法可以大大简化Java程序中的文件操作,提高开发效率。其中,常用的方法包括: 1. FileUtils.readFileToString(File file, Charset encoding):读取指定文件并返回字符串。 2. FileUtils.write(File file, CharSequence data, Charset encoding):将指定字符串写入指定文件。 3. FileUtils.copyFile(File srcFile, File destFile):复制指定文件到目标文件。 4. FileUtils.deleteQuietly(File file):删除指定文件,如果文件不存在则不会抛出异常。 需要注意的是,在使用这些方法之前,需要先导入Apache Commons Lang3工Apache文件工具类是Apache Commons Lang3工具包中的一个类,提供了一系列用于文件操作的方法,例如读取文件、写入文件、复制文件、删除文件等。这些方法可以大大简化Java程序中的文件操作,提高开发效率。其中,常用的方法包括: 1. FileUtils.readFileToString(File file, Charset encoding):读取指定文件并返回字符串。 2. FileUtils.write(File file, CharSequence data, Charset encoding):将指定字符串写入指定文件。 3. FileUtils.copyFile(File srcFile, File destFile):复制指定文件到目标文件。 4. FileUtils.deleteQuietly(File file):删除指定文件,如果文件不存在则不会抛出异常。 需要注意的是,在使用这些方法之前,需要先导入Apache Commons Lang3工具包,并在代码中引入相应的类。例如,要使用FileUtils类中的方法,需要在代码中添加import org.apache.commons.io.FileUtils;语句。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值