`
zheng_liming
  • 浏览: 8397 次
  • 性别: Icon_minigender_1
  • 来自: 湖北宜昌
社区版块
存档分类
最新评论

文件操作工具类

 
阅读更多

        自己写的文件操作工具类,供以后翻阅查看:

 

public class FileUtil {
	private static Logger logger = LogFactory.getLog(FileUtil.class);

	/**
	 * 当前的classpath的绝对路径
	 * 
	 * @return
	 */
	public static String getClassPath() {
		URL url = Thread.currentThread().getContextClassLoader()
				.getResource("");
		String path = url.toString();
		if (path.startsWith("file:")) {
			path = path.substring(6);
		}
		return path;
	}

	/**
	 * 获得项目根目录的绝对路径 
	 * @return default value is null
	 */
	public static String getProjectPath() {
		//默认NULL
		return System.getProperty(SystemConstants.PROJECT_PATH, null);
	}

	/**
	 * 创建文件夹
	 * @param strFilePath
	 *            文件夹路径
	 */
	public static boolean mkdirFolder(String strFilePath) {
		boolean bFlag = false;
		try {
			File file = new File(strFilePath.toString());
			if (!file.exists()) {
				bFlag = file.mkdir();
			}
		} catch (Exception e) {
			logger.error("新建目录操作出错" + e.getLocalizedMessage());
			e.printStackTrace();
		}
		return bFlag;
	}

	/**
	 * 创建文件
	 * @param strFilePath
	 * @return
	 */
	public static boolean createFile(String strFilePath) {
		boolean bFlag = false;
		try {
			File file = new File(strFilePath.toString());
			if (!file.exists()) {
				bFlag = file.createNewFile();
			}
		} catch (Exception e) {
			logger.error("新建文件操作出错" + e.getLocalizedMessage());
			e.printStackTrace();
		}
		return bFlag;
	}

	/**
	 * 删除文件
	 * @param strFilePath
	 * @return
	 */
	public static boolean removeFile(String strFilePath) {
		boolean result = false;
		if (strFilePath == null || "".equals(strFilePath)) {
			return result;
		}
		File file = new File(strFilePath);
		if (file.isFile() && file.exists()) {
			result = file.delete();
			if (result == Boolean.TRUE) {
				logger.debug("[REMOE_FILE:" + strFilePath + "删除成功!]");
			} else {
				logger.debug("[REMOE_FILE:" + strFilePath + "删除失败]");
			}
		}
		return result;
	}

	/**
	 * 删除文件夹(包括文件夹中的文件内容,文件夹)
	 * @param strFolderPath
	 * @return
	 */
	public static boolean removeFolder(String strFolderPath) {
		boolean bFlag = false;
		try {
			if (strFolderPath == null || "".equals(strFolderPath)) {
				return bFlag;
			}
			File file = new File(strFolderPath.toString());
			bFlag = file.delete();
			if (bFlag == Boolean.TRUE) {
				logger.debug("[REMOE_FOLDER:" + file.getPath() + "删除成功!]");
			} else {
				logger.debug("[REMOE_FOLDER:" + file.getPath() + "删除失败]");
			}
		} catch (Exception e) {
			logger.error("FLOADER_PATH:" + strFolderPath + "删除文件夹失败!");
			e.printStackTrace();
		}
		return bFlag;
	}

	/**
	 * 移除所有文件
	 * @param strPath
	 */
	public static void removeAllFile(String strPath) {
		File file = new File(strPath);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] fileList = file.list();
		File tempFile = null;
		for (int i = 0; i < fileList.length; i++) {
			if (strPath.endsWith(File.separator)) {
				tempFile = new File(strPath + fileList[i]);
			} else {
				tempFile = new File(strPath + File.separator + fileList[i]);
			}
			if (tempFile.isFile()) {
				tempFile.delete();
			}
			if (tempFile.isDirectory()) {
				removeAllFile(strPath + "/" + fileList[i]);// 下删除文件夹里面的文件
				removeFolder(strPath + "/" + fileList[i]);// 删除文件夹
			}
		}
	}

	/**
	 * 复制文件
	 * @param oldPath 源路径
	 * @param newPath 目标路径
	 */
	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				fs.close();
				inStream.close();
				logger.debug("[COPY_FILE:" + oldfile.getPath() + "复制文件成功!]");
			}
		} catch (Exception e) {
			System.err.println("复制单个文件操作出错 ");
			e.printStackTrace();
		}
	}

	/**
	 * 复制文件夹
	 * @param oldPath 源路径
	 * @param newPath 目标路径
	 */
	public static void copyFolder(String oldPath, String newPath) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
					logger.debug("[COPY_FILE:" + temp.getPath() + "复制文件成功!]");
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/"
							+ file[i]);
				}
			}
		} catch (Exception e) {
			System.err.println("复制整个文件夹内容操作出错 ");
			e.printStackTrace();
		}
	}

	/**
	 * 写入文件
	 * @param filePath 文件路径
	 * @param content	文件内容
	 * @return
	 */
	public static boolean writeFile(String filePath, String content) {
		try {
			File f = new File(filePath);
			
			if(f.isDirectory())
			{
				logger.error("路径"+filePath+"错误,目标文件不能为目录");
				return false;
			}
			File parentF = f.getParentFile();
			if(!parentF.exists()){
				
				parentF.mkdirs();
				logger.info("创建目录");
			}
			
			FileWriter fw = new FileWriter(filePath);
			long begin3 = System.currentTimeMillis();

			fw.write(content);

			fw.close();

			long end3 = System.currentTimeMillis();

			logger.info("执行文件写入耗时" + (end3 - begin3) + " 毫秒");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(filePath+"文件写入失败");
			return false;
		}		
	}
	
	/**
	 * 列出目录下的对应的文件名
	 * @param lstFileNames
	 * @param f
	 * @param suffix
	 * @param isdepth
	 * @return
	 */
	public static List<String> listFile(List<String> lstFileNames, File f, String suffix, boolean isdepth) {  
		  // 若是目录, 采用递归的方法遍历子目录    
		  if (f.isDirectory()) {  
		   File[] t = f.listFiles();  
		   for (int i = 0; i < t.length; i++) {  
		    if (isdepth || t[i].isFile()) {  
		     listFile(lstFileNames, t[i], suffix, isdepth);  
		    }  
		   }     
		  } else {  
		   String filePath = f.getAbsolutePath();     
		   if (!suffix.equals("")) {  
		    int begIndex = filePath.lastIndexOf("."); // 最后一个.(即后缀名前面的.)的索引  
		    String tempsuffix = "";  
		    if (begIndex != -1) {  
		     tempsuffix = filePath.substring(begIndex, filePath.length());  
		     if (tempsuffix.equals(suffix)) {  
		      lstFileNames.add(f.getName());  
		     }  
		    }  
		   } else {  
		    lstFileNames.add(f.getName());  
		   }  
		  }  
		  return lstFileNames;  
		 } 

	/**
	 * 列出目录下的对应的文件名
	 * @param lstFilePaths
	 * @param f
	 * @param suffix
	 * @param isdepth
	 * @return
	 */
	public static List<String> listFilePath(List<String> lstFilePaths, File f, String suffix, boolean isdepth) {  
		  // 若是目录, 采用递归的方法遍历子目录    
		  if (f.isDirectory()) {  
			  File[] t = f.listFiles();  
			  for (int i = 0; i < t.length; i++) {  
				  if (isdepth || t[i].isFile()) {  
					  listFilePath(lstFilePaths, t[i], suffix, isdepth);  
				  }  
			  }     
		  } else {  
			  String filePath = f.getAbsolutePath();     
			  if (!suffix.equals("")) {  
				  int begIndex = filePath.lastIndexOf("."); // 最后一个.(即后缀名前面的.)的索引  
				  String tempsuffix = "";  
				  if (begIndex != -1) {  
					  tempsuffix = filePath.substring(begIndex, filePath.length());  
					  if (tempsuffix.equals(suffix)) {
						  lstFilePaths.add(filePath);
					  }  
				  }  
			  }  
		  }  
		  return lstFilePaths;  
	} 
	
	/**
	 * 上传文件到ftp上(将项目运行的电脑即服务器上将文件传入ftp,而非客户端)
	 * @param ftpClient ftp连接
	 * @param remoteFilePath ftp文件保存路径
	 * @param localFilePath 服务器文件路径
	 * @return boolean 上传是否成功
	 */
	public static boolean ftpUpload(FtpClient ftpClient,String remoteFilePath,String localFilePath) {
		try {
			TelnetOutputStream os = ftpClient.put(remoteFilePath);
			java.io.File file_in = new java.io.File(localFilePath);
			FileInputStream is = new FileInputStream(file_in);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
			is.close();
			os.close();
			return true;
		} catch (IOException e) {
			System.out.println("ftp文件上传失败!");
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 下载ftp上的文件(下载到项目运行的电脑上,即服务器,而非客户端)
	 * @param ftpClient ftp连接
	 * @param remoteFilePath ftp文件路径
	 * @param localFilePath 服务器保存路径
	 * @return boolean 下载是否成功
	 */
	public static boolean ftpDownload(FtpClient ftpClient,String remoteFilePath,String localFilePath) {
		try {
			TelnetInputStream is = ftpClient.get(remoteFilePath);
			java.io.File file_in = new java.io.File(localFilePath);
			FileOutputStream os = new FileOutputStream(file_in);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
			os.close();
			is.close();
			return true;
		}catch(IOException e) {
			System.out.println("ftp文件下载失败!");
			e.printStackTrace();
			return false;
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics