java web文件相关操作

一. 文件上传

(1)使用FileUtils.copyInputStreamToFile上传,若上传目录不存在,工具类会帮忙创建目录

   /** 
	* @Title: roadFileAddUpload 
	* @Description: 新增多个文件上传功能
	* @param myfile
	* @return
	* @throws Exception   
	*/
   @RequestMapping({ "road/roadfileaddupload" })
   public String roadFileAddUpload( @RequestParam("attachUp") MultipartFile myfile)                     
     throws Exception {
		String id = this.request.getParameter("id");		
		//1. 判断文件格式是否正确
		String filename = myfile.getOriginalFilename();
		ConfigUtil conf = ConfigUtil.getInstance();
		String rightFiles = conf.getValue("rightFiles");
		String[] files = rightFiles.split(",");
		boolean flag = false;
		for(String f : files){
			if(filename.endsWith(f)){
				flag = false;
				break;
			}
			flag = true;
		}
		if(flag ){			
			return "redirect:/test/testFile.action?id=" + id;
		}			
	    //2. 判断数据库中是否已有该文件
        // ...

        //3. 判断文件大小是否超过最大大小
		String extStr = "";// 文件后缀
		String issueStr = "";
		String name = "";
		this.uploadSize = Integer
				.parseInt(this.rb.getString("ATTACHMENT_SIZE"));
		if (!myfile.isEmpty()) {
			if (myfile.getSize() > this.uploadSize * 1024 * 1024) {
				return "redirect:/test/testFile.action?id=" + id;
			}
			
			extStr = FileUtils.getExt(myfile.getOriginalFilename());

			name = TimeUtil.getCurrentDate("yyyyMMdd")
					+ myfile.getOriginalFilename();
			if (attach == null || attach.equals("")) {
				issueStr = name;
			} else {
				issueStr = attach + ";" + name;
			}
			
		}
		
		//4. 保存新上传的文件
		String savePath = conf.getValue("SAVE_ATTACHMENT");		
		//解决上传中文文件下载下来文件无法打开的问题
		logger.info("name: " + name);
		logger.info("name GB18030: " + new String(name.getBytes("utf-8")
				, "GB18030"));
		/*name = new String(name.getBytes("utf-8")
				, "GB18030");*/
			
		if (!myfile.isEmpty()) {
			FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(
					savePath, name));
			//5.更新数据库中文件名字段
            // ...
		}//myfile is not empty
		
		return "redirect:/test/testFile.action?id=" + id;
    }

(2) 使用multipartFile.transferTo(newFilePath)上传文件,需要提前创建文件存放目录

    // 批量导入历史记录
    @RequestMapping(value = "importRecordList")
    public ModelAndView importRecordList(HttpServletRequest request,
                                        HttpServletResponse response) throws Exception{

        ResponseInfo responseInfo = new ResponseInfo();
        try {
            //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
            CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                    request.getSession().getServletContext());

            // 判断是否是多数据段提交格式
            if (multipartResolver.isMultipart(request)) {

                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                Iterator<String> iter = multiRequest.getFileNames();
                logger.info("iter.hasNext(): "+iter.hasNext());

               
                Integer fileCount = 0;

                while (iter.hasNext()) {
                    MultipartFile multipartFile = multiRequest.getFile(iter.next());
                    String fileName = multipartFile.getOriginalFilename();

                    logger.info("upload filename: " + fileName );

                    if(fileName == null || fileName.trim().equals("")){
                        continue;
                    }

                    //20170207 针对IE环境下filename是整个文件路径的情况而做以下处理
                    Integer index = fileName.lastIndexOf("\\");
                    String newStr = "";
                    if(index>-1){
                        newStr = fileName.substring(index+1);
                    }else{
                        newStr = fileName;
                    }
                    if(!newStr.equals("")){
                        fileName = newStr;
                    }
                    logger.info("new filename: " + fileName );

                    if (multipartFile != null) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                        String now = df.format(new Date());// new Date()为获取当前系统时间
                        logger.info("now: " + now);

                        String tempPath=System.getProperty("user.dir");
                        //C:\Users\alibaba\AppData\Local\Temp\tomcat-docbase.8773812282408690471.7001\
                        logger.info(request.getSession().getServletContext().getRealPath("") );
                        //null
                        logger.info(request.getSession().getServletContext().getRealPath("../") );
                        logger.info(System.getProperty("user.dir") );//项目的根路径

                        File existPath = new File(tempPath);
                        if (!existPath.exists()) {
                            existPath.mkdirs();//不存在则创建此文件夹
                        }
                        String absoluteFilePath = existPath.getAbsolutePath();
                        logger.info("dest absoluteFilePath: " + absoluteFilePath);
                        String path ="";
                        String newFileName = now+"_" + fileName;
                        path = absoluteFilePath + File.separator + newFileName;

                        logger.info("文件路径: " + path);

                        //上传
                        multipartFile.transferTo(new File(path));

                        //获取文件扩展名
                        Integer tempIndex = newFileName.lastIndexOf('.');
                        Integer fileNameLength = newFileName.length();
                        String extendName = newFileName.substring(tempIndex+1, fileNameLength);
                        logger.info("文件扩展名: " + extendName);
                        HashMap<String,Object> contentMap = new HashMap<String,Object>();
                        if(extendName != null && !extendName.equals("")){
                            contentMap = ExcelReader.read(path,extendName);
                            Boolean success = (Boolean)contentMap.get("success");

                            if(success.equals(true)){//Excel读取成功

                                List<List<Object>> dataList = (List<List<Object>>)contentMap.get("dataList");

                                if(dataList != null && dataList.size() > 1){
                                    if(dataList.size()-1>Constants.MAX_IMPORT_BATCH_SIZE){
                                        responseInfo.setStatus(false);
                                        responseInfo.setMsg("一次导入数量不得超过" + Constants.MAX_IMPORT_BATCH_SIZE);
                                    }else {
                                        
                                        HashMap<String, Object> result = this.accordService.importRecordList(contentMap);

                                        boolean success2 = (boolean) result.get("success");
                                        String msg = (String) result.get("msg");

                                        Integer count = (Integer)result.get("count");

                                        responseInfo.put("count", count);
                                        responseInfo.setStatus(success2);
                                        responseInfo.setMsg(msg);
                                        
                                    }

                                }else{
                                    responseInfo.setStatus(false);
                                    responseInfo.setMsg("Excel内容为空");
                                }
                            }else{
                                responseInfo.setStatus(false);
                                responseInfo.setMsg((String)contentMap.get("msg"));
                            }

                        }else{
                            responseInfo.setStatus(false);
                            responseInfo.setMsg("输入的Excel文件格式不正确");
                        }

                        //删除路径下的文件
                        File deleteFile = new File(path);
                        if(deleteFile.exists()) {
                            logger.info("delete file: " + path);
                            deleteFile.delete();
                        }

                    }
                    fileCount++;
                }//while
                logger.info("fileCount: " + fileCount);
            }
        }catch (Exception e) {
            // TODO: handle exception
            responseInfo.setStatus(false);
            responseInfo.setMsg("后台出现异常");
            logger.warn("Error: ", e);

        }

        response.setContentType("text/html; charset=utf-8");
        response.getWriter().write(JSON.toJSONString(responseInfo));

        return null;
    }

二. 文件下载

@RequestMapping("common/download")
	public void download(HttpServletRequest request,HttpServletResponse response) throws IOException{
		ConfigUtil conf = ConfigUtil.getInstance();
		if (FilterUtil.myFilter(request)==false) {
		    session.setAttribute("fileDownload", 0);
		}else{
		String filePath = "";
		logger.info("filename1: " + request.getParameter("filename"));
		//logger.info("filename2: " + new String(request.getParameter("filename").getBytes("ISO8859-1"),"UTF-8"));
		//logger.info("filename3: " + new String(request.getParameter("filename").getBytes("GB18030"),"UTF-8"));
		//logger.info("filename4: " + new String(request.getParameter("filename").getBytes("utf-8"),"UTF-8"));
		
		//文件名转码 20150908 update
		//String filename = new String(request.getParameter("filename").getBytes("ISO8859-1"),"UTF-8");
		String filename = request.getParameter("filename");
	    
		//修复路径遍历漏洞
		filename = FilePath.pathFilter(filename);
		logger.info("after pathFilter fileName: " + filename); 
		
		//修正下载漏洞
		String rightFiles = conf.getValue("rightFiles");
		String[] files = rightFiles.split(",");
		boolean flag = false;
		for(String f : files){
			if(filename.endsWith(f)){
				flag = false;
				break;
			}
			flag = true;
		}
		if(flag){
			session.setAttribute("fileDownload", 0);
			return;
		}
		if(filename != null && filename.contains("../")){
			session.setAttribute("fileDownload", 0);
			return;
		}
		
		String status = request.getParameter("status")==null?"":request.getParameter("status");
		String type = request.getParameter("type");
		if(filename == null || type == null){
			session.setAttribute("fileDownload", 0);
		}else if(type.equals("r_csv")){ //csv导出
			filePath = conf.getValue("CSV_EXPORT") + filename;
		}else if(type.equals("r_attach")){ //附件导出
			filePath = conf.getValue("ATTACHMENT_PATH") + filename;
		}else{ //模板等文件下载
			filePath = conf.getValue("FILES") + filename;
		}
		filePath = filePath.replace("\\","/");
		logger.info("Download Path: " + filePath);
		filePath = new String(filePath.getBytes("utf-8")
				, "GB18030");
		logger.info("Download Path after encoding: " + filePath);
		
		//response.setCharacterEncoding("gbk"); 
		response.setContentType("application/octet-stream;charset=utf-8");
		//response.addHeader("Content-Disposition","attachment;filename=" + new String(filename.getBytes("utf-8"),"iso-8859-1"));
		logger.info("filename 1: " + new String(filename.getBytes("utf-8"),"iso-8859-1"));
		String tempStr = new String(filename.getBytes("utf-8")
				, "GB18030");
		logger.info("filename 2: " + tempStr);
		logger.info("filename 3: " + new String(tempStr.getBytes("GB18030"),"iso-8859-1"));	
		//20171026 显式设置下载文件名称
		String fileShowName = request.getParameter("showName");
		if(fileShowName != null && !fileShowName.equals("")){
			tempStr = new String(fileShowName.getBytes("utf-8")
					, "GB18030");
		}
		
		response.addHeader("Content-Disposition","attachment;filename=" + new String(tempStr.getBytes("GB18030"),"iso-8859-1"));	
		OutputStream outp = null;
		FileInputStream in = null;
		try{			
				if(filename.contains("http:")){//url地址 									   
						if(!FileUtils.isURLInWhiteList(filename)){//不在白名单里的域名
								return;						
						}
						
						HttpURLConnection httpUrl = null;
						URL url = null;
						BufferedInputStream bis = null;						
						url = new URL(filename);						
						httpUrl = (HttpURLConnection) url.openConnection();					
						// 修复漏洞
						httpUrl.setInstanceFollowRedirects(false);						
						httpUrl.connect();
						bis = new BufferedInputStream(httpUrl.getInputStream());						
						outp = response.getOutputStream();
						byte[] b = new byte[1024];
						int i = 0;
						while((i = bis.read(b)) > 0){
						        outp.write(b, 0, i);
						}
						outp.flush();
						outp.close();
						httpUrl.disconnect();
						bis.close();
						outp=null;
				}else{				    
							
					in = new FileInputStream(filePath);
				    outp = response.getOutputStream();
				    byte[] b = new byte[1024];
				    int i = 0;
				    while((i = in.read(b)) > 0){
				        outp.write(b, 0, i);
				    }
				    outp.flush();
				    outp.close();
				    outp=null;
				}
			    
			    response.flushBuffer();			    
			    logger.info("no error " );			
		}
		catch(FileNotFoundException e){
		    System.out.println("Error!!");
		    logger.info("FileNotFoundException e: " + e);
		    e.printStackTrace();
		    session.setAttribute("fileDownload", 0);
		}
		finally{
			if(in != null){
				in.close();
				in = null;
			}
			if(outp != null){
				outp.close();
				outp = null;
		    }
		}
		}
		session.setAttribute("fileDownload", 1);

	} 

三. 其他文件操作(压缩等)

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


/**
 * 文件处理类,压缩,解压缩等
 * 
 * @author v-zhuchaoqun
 * @create 20121105
 * 
 */

public class FileUtils extends org.apache.commons.io.FileUtils {

	private String filePath; // Zip文件的路径
	private ZipOutputStream zos; // Zip文件输出流
	private final int BUFFER = 4096; // 缓冲区大小
	private static Logger logger = Logger.getLogger(FileUtils.class.getName());

	public FileUtils() {
		// Constructor
	}

	public FileUtils(String filePath) {
		// 初始化Zip文件的路径
		this.filePath = filePath;
		// 生成Zip文件
		makeZipFile();
	}

	/**
	 * 创建文件目录
	 * 
	 * @param directory
	 * @param subDirectory
	 */
	public static void createDirectory(String directory, String subDirectory) {
		String dir[];
		File fl = new File(directory);
		try {
			// 如果解压文件基本目录结构不存在,新建
			if (subDirectory == "" && fl.exists() != true) {
				// System.out.println("*******创建基本目录结构*******"+directory);
				fl.mkdir();
			}
			// 主要创建子目录
			else if (subDirectory != "") {
				dir = subDirectory.replace('\\', '/').split("/");
				for (int i = 0; i < dir.length; i++) {
					File subFile = new File(directory + File.separator + dir[i]);
					if (subFile.exists() == false) {
						// System.out.println("*******创建子目录*******"+directory +
						// File.separator + dir[i]);
						subFile.mkdir();
					}
					directory += File.separator + dir[i];
				}
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

	/**
	 * 解压*.zip格式文件
	 * 
	 * @param zipFileName
	 *            文件名
	 * @param outputDirectory
	 *            解压路径
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String extractZip(String zipFileName, String outputDirectory)
			throws Exception {
		System.out.println(zipFileName);
		String fileStr = ""; // log记录,解压的文件名
		org.apache.tools.zip.ZipFile zipFile = null;
		try {
			//20160318
			zipFile = new org.apache.tools.zip.ZipFile(zipFileName,"GBK");
			java.util.Enumeration e = zipFile.getEntries();
			org.apache.tools.zip.ZipEntry zipEntry = null;
			createDirectory(outputDirectory, "");
			while (e.hasMoreElements()) {
				zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
				logger.info("========== 解压 ========== "
						+ zipEntry.getName());
				// fileStr += zipEntry.getName() + "@@";
				// 判断是否为一个文件夹
				if (zipEntry.isDirectory()) {
					String name = zipEntry.getName().trim();
					// 因为后面带有一个/,所有要去掉
					name = name.substring(0, name.length() - 1);
					File f = new File(outputDirectory + File.separator + name);
					if (!f.exists()) {
						f.mkdir();
					}
					// System.out.println("*******创建根目录*******" +
					// outputDirectory + File.separator + name);
				} else {
					String fileName = zipEntry.getName();
					fileName = fileName.replace('\\', '/');
					fileStr += fileName + "@@";
					// 判断子文件是否带有目录,有创建,没有写文件
					if (fileName.indexOf("/") != -1) {
						createDirectory(outputDirectory, fileName.substring(0,
								fileName.lastIndexOf("/")));
						fileName = fileName
								.substring(fileName.lastIndexOf("/") + 1);
						// fileStr = fileStr + fileName + "\r\n";
					}
                    
					//20151209 add
					String extractPath = outputDirectory + File.separator
							+ zipEntry.getName();
					
					//20160318
					//File f = new File(new String(extractPath.getBytes("utf-8"), "GB18030"));
					File f = new File(encodeForServer(extractPath));
					
					logger.info(outputDirectory + File.separator
							+ zipEntry.getName());
					logger.info("encodeForServer(extractPath): " + encodeForServer(extractPath));
					logger.info("GB18030 extract file: "+ new String(extractPath.getBytes("utf-8")
							, "GB18030"));
					
					f.createNewFile();
					
					InputStream in = zipFile.getInputStream(zipEntry);
					FileOutputStream out = new FileOutputStream(f);

					byte[] by = new byte[1024];
					int c;
					
					while ((c = in.read(by)) != -1) {
						out.write(by, 0, c);
					}
					in.close();
					out.close();
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage());
		} finally {
			zipFile.close();
		}
		logger.info(fileStr + "\n" + "^^^^^^^^^^ 解压完成 ^^^^^^^^^^");
		return fileStr;
	}

	/**
	 * 创建*.zip文件
	 */
	public void makeZipFile() {
		try {
			zos = new ZipOutputStream(new FileOutputStream(filePath));
			// 设置ZIP文件注释
			// String comment = "Make images import *.zip file";
			// zos.setComment(comment);
			zos.setEncoding("gbk");
			// 设置用于后续条目的默认压缩方法
			zos.setMethod(ZipOutputStream.DEFLATED);
		} catch (FileNotFoundException e) {
			logger.error("[生成Zip文件失败] " + e);
		}
	}

	/**
	 * 将目标文件夹写入Zip
	 * 
	 * @param targetFolder
	 *            需要压缩的文件(目录)
	 * @return 写入成功,返回true;失败,返回false
	 */
	public boolean packToZip(String targetFolder) {
		try {
			File folder = new File(targetFolder + "/");
			if (folder.isDirectory()) {
				File[] files = folder.listFiles();
				for (File file : files) {
					System.out.println("Files in folder: " + file.getName());
					// 目录下的文件添加到*.zip
					writeZipFile(targetFolder + "/" + file.getName());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Fail");
			return false;
		} finally {
			closeZipOutputStream();

		}
		return true;
	}

	/**
	 * 将一个文件写入*.zip
	 * 
	 * @param targetFile
	 *            目标文件
	 * @return 写入成功,返回true;失败,返回false
	 */
	public boolean writeZipFile(String targetFile) {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			// 创建文件输入流对象
			fis = new FileInputStream(targetFile);
			bis = new BufferedInputStream(fis, BUFFER);
			// 获取目录结构
			String[] array = targetFile.replace("\\", "/").split("/");
			int length = array.length;
			String str = "";
			if (array[length - 2] == null || array[length - 2].equals(""))
				str = "";
			else
				str = array[length - 2] + "/";
			logger.info("File to Zip: " + str + array[length - 1]
					+ ", length: " + targetFile.length());
			
			//20151102 为防止压缩文件中文件乱码
			String tempStr = str + array[length - 1];
			tempStr	= encodeForServer(tempStr);
			logger.info("encodeForServer tempStr: " + tempStr);
			logger.info("tempStr2: " + new String(tempStr.getBytes("GB18030"),"utf-8"));
			
			ZipEntry entry = new ZipEntry(tempStr);
		    //ZipEntry entry = new ZipEntry(str + array[length - 1])
			
			// 设置压缩文件大小
			entry.setCompressedSize(2048);
			zos.putNextEntry(entry);
		
			int count;
			byte[] buffer = new byte[BUFFER];
			while ((count = bis.read(buffer, 0, BUFFER)) != -1) {
				zos.write(buffer, 0, count);
			}
		} catch (Exception e) {
			logger.warn("[向Zip中添加文件失败] " + e);
		} finally {
			try {
				fis.close();
				bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * 关闭Zip输出流
	 */
	public void closeZipOutputStream() {
		try {
			zos.close();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("[关闭Zip输出流错误] " + e);
		}
	}

	
	/**
	 * 复制文件到指定路径
	 * 
	 * @param fromPath
	 *            原路径(包含文件名)
	 * @param destPath
	 *            目标路径
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	// public boolean CopyFiles(String fromPath, String destPath, String
	// filename){
	public static boolean CopyFiles(String fromPath, String destPath) throws UnsupportedEncodingException {
		System.out.println("From:" + fromPath + " to:" + destPath);
		String srcPath = fromPath.replace("\\", "/");
		String[] srcArr = srcPath.split("/");
		// System.out.println("filePath:" + srcPath.substring(0,
		// srcPath.lastIndexOf("/")));
		String filename = srcArr[srcArr.length - 1];
		
		//20151111 处理从用户反馈回来的附件  暂时还没拷贝到高快服务器上
		String str = filename.trim();
		String[] strArr = str.split("/");
		if(strArr.length>1 && strArr[0].equals("http:")){//用户反馈回来的附件
			logger.info("filename - " + filename + " cannot download");
			return false;
		}
		
		// System.out.println("filename:" + filename);
		String ext = "";
		try {
			if(filename.lastIndexOf(".")<0){
				logger.info("filename - " + filename + " : 无法获取扩展名"); 
				return false;
			}
			ext = filename.substring(filename.lastIndexOf("."),
					filename.length());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}

		String tgtPath = destPath.replace("\\", "/");
		String[] destArr = tgtPath.split("/");
		String newfilename = "";
		if (destArr[destArr.length - 1].indexOf(".") == -1) {
			newfilename = srcArr[srcArr.length - 1];
			tgtPath = destPath.replace("\\", "/") + newfilename;
		} else { // 包含文件名,则重命名
			newfilename = destArr[destArr.length - 1].substring(0,
					destArr[destArr.length - 1].lastIndexOf(".")) + ext;
			tgtPath = destPath.replace("\\", "/");
			tgtPath = tgtPath.substring(0, tgtPath.lastIndexOf("/") + 1)
					+ newfilename;
		}
		// System.out.println("new filename:" + newfilename);
		// System.out.println("Target filename:" + tgtPath);
		logger.info("From srcPath: " + srcPath + " to tgtFile: "
				+ tgtPath);
		
		//2015092
		tgtPath = new String(tgtPath.getBytes("utf-8")
				, "GB18030");
		logger.info("encoding GB18030 tgtPath: " + tgtPath);
		
		//20151102
		srcPath = new String(srcPath.getBytes("utf-8")
				, "GB18030");
		logger.info("encoding GB18030 srcPath: " + srcPath);
		
		File srcFile = new File(srcPath);
		File tgtFile = new File(tgtPath);
		// 判读要复制的文件是否存在
		if (!srcFile.exists()) {
			// System.out.println(srcFile.getName() + "源文件不存在");
			return false;
		} else {
			// System.out.println("源文件存在");
		}
		// 创建新文件
		try {
			// 若存在同名的文件
			if (tgtFile.exists()) {
				tgtFile.delete();
				// System.out.println("The existed file has been deleted!");
			} else {
				// System.out.print("A new file...");
				// 创建新文件
				tgtFile.createNewFile();
				// System.out.println(" has been created!");
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("[创建文件失败] " + e);
			return false;
		}
		// 复制文件
		byte[] b = new byte[(int) srcFile.length()];
		if (srcFile.isFile()) {
			FileInputStream is = null;
			FileOutputStream ps = null;
			try {
				is = new FileInputStream(srcPath.replace("\\", "/"));
				ps = new FileOutputStream(tgtPath.replace("\\", "/"));
				is.read(b);
				ps.write(b);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("[复制文件失败] " + e);
				return false;
			} finally {
				try {
					is.close();
					ps.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return true;
	}

	/**
	 * 导航反馈附件,移动并重命名
	 * 
	 * @param fromPath
	 *            源地址
	 * @param destPath
	 *            目标地址
	 * @param filename
	 *            文件名
	 */
	public static boolean MoveAndRename(String fromPath, String destPath,
			String tag) {
		String srcPath = fromPath.replace("\\", "/");
		String[] dirArr = srcPath.split("/");
		System.out.println("filePath:"
				+ srcPath.substring(0, srcPath.lastIndexOf("/")));
		// 原文件名
		System.out.println("filename:" + dirArr[dirArr.length - 1]);
		// 移动文件的路径和新文件名
		String tgtPath = destPath.replace("\\", "/")
				+ dirArr[dirArr.length - 1];
		System.out.println("Target filename:" + tgtPath);
		System.out.println("From srcPath: " + srcPath + " to tgtFile: "
				+ tgtPath);
		File srcFile = new File(srcPath);
		File tgtFile = new File(destPath);
		// 判读要复制的文件是否存在
		if (!srcFile.exists()) {
			System.out.println(srcFile.getName() + "源文件不存在");
			return false;
		} else {
			System.out.println("源文件存在");
		}
		// 创建新文件
		try {
			// 若存在同名的文件
			if (tgtFile.exists()) {
				tgtFile.delete();
				System.out.println("The existed file has been deleted!");
			} else {
				System.out.print("A new file...");
				// 创建新文件
				tgtFile.createNewFile();
				System.out.println(" has been created!");
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("[创建文件失败] " + e);
			return false;
		}
		// 复制文件
		byte[] b = new byte[(int) srcFile.length()];
		FileInputStream is = null;
		FileOutputStream ps = null;
		if (srcFile.isFile()) {
			try {
				is = new FileInputStream(srcPath.replace("\\", "/"));
				ps = new FileOutputStream(tgtPath.replace("\\", "/"));
				is.read(b);
				ps.write(b);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("[复制文件失败] " + e);
				return false;
			} finally {
				try {
					is.close();
					ps.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return true;
	}

	public static String getExt(String str) {
		return str.substring(str.lastIndexOf("."), str.length());
	}

	// ---------------------------用户批量上报---------------------------------
	/**
	 * 
	 * Description: 复制一份新的文件到指定的目录,如果与目录内的文件重名,则重新命名上传文件
	 * 
	 * @param : File f 要被copy的文件
	 * @param : String filename 命名copy后文件的名称
	 * @param : String path 指定copy文件的目录
	 */
	public static String copyFile(File f, String filename, String path) {// copy一份新的文件到指定路径

		File ff = new File(path);
		if (!ff.exists())
			ff.mkdirs();
		List li = listFile(ff);
		while (li.contains(filename)) {
			filename = reFilenameTo(filename);// 假如目录里有同名文件,则重新命名上传文件名称
		}
		String pathfile = path + "/" + filename;
		File newfile = new File(pathfile);
		copy(f, newfile); // 复制文件
		return filename;
	}

	/**
	 * Description: 返回文件目录下的所以文件名称集合
	 * 
	 * @param : File directory 文件目录路径
	 * @return: List 包含目录下所有的文件名称
	 */
	public static List listFile(File directory) {
		List list = new ArrayList();
		File listfile[] = directory.listFiles();
		for (int i = 0; i < listfile.length; i++) {
			File f = listfile[i];
			if (f.isFile())
				list.add(f.getName());
		}

		return list;
	}

	/**
	 * Description: 返回文件目录下的所以文件名称集合
	 * 
	 * @param : String filename 重新命名这个文件名称,默认在文件名称末尾加1
	 * @return: String 文件新的名称的字符串
	 */
	public static String reFilenameTo(String filename) {
		int index = filename.lastIndexOf(".");
		if (index > 0) {
			String frontname = filename.substring(0, index);
			String behindname = filename.substring(index, filename.length());
			return frontname + 1 + behindname;
		} else {
			return filename + 1;
		}
	}

	/**
	 * Description: 文件的复制
	 * 
	 * @param : File fromFile
	 * @param : File toFile
	 */
	public static void copy(File fromFile, File toFile) {
		try {
			FileChannel srcChannel = new FileInputStream(fromFile).getChannel();
			FileChannel dstChannel = new FileOutputStream(toFile).getChannel();
			dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
			srcChannel.close();
			dstChannel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	// -------------------------------------------------------------------------------
    
	// 测试域名是否在白名单中
	public static boolean isURLInWhiteList(String urlStr) throws MalformedURLException{
		
		URL url = new URL(urlStr);
		
		String host = url.getHost();
		
		logger.info("url: " + urlStr + "; host: " + host); 
		
		List<String> validURLArr = Constants.validURLArr;
		for(int i=0; i<validURLArr.size(); i++){
			if(host.contains(validURLArr.get(i))){
				logger.info("in white list");
				return true;
			}
		}
		
		logger.info("not in white list");
		return false;
		
	}
	
	public static String encodeForServer(String str) throws UnsupportedEncodingException{
		return new String(str.getBytes("utf-8"), "utf-8");
	}
	
	public static void main(String[] args) throws Exception {
		// 解压缩测试
		 //extractZip("D:/test_files/Test4.zip","D:/test_files/Test4"); //路径后不用加'/'
		// 压缩文件测试
		 FileUtils fu = new FileUtils("D:/test_files/ziptarget");
		 fu.packToZip("D:/test_files/zip1111");
		 
		// 文件移动测试
		//FileUtils fu = new FileUtils();
		// fu.CopyFiles("e:/tt/","e:\\test\\","123.txt"); //加'/'
		//CopyFiles("e:/tt/123.txt", "e:\\road_fbAttachments\\tgtPath");
		
		//20160316 查看系统编码
		//String encoding = System.getProperty("file.encoding");  
       // System.out.println("Encoding:" + encoding);
	}
    
	
}

猜你喜欢

转载自blog.csdn.net/xyr05288/article/details/84494045