工程作完了,总结下用到的文件操做java
package com.cheqiren.caren.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** 程序名 FileUtils.java 程序功能 文件/文件夹 建立及删除 做成者 xxx 做成日期 2015-11-06 ======================修改履历====================== 项目名 状态 做成者 做成日期 -------------------------------------------------- caren 新规 xxx 2015-11-06 ================================================= */ public class FileUtils { /** * 删除单个文件 * @param sPath 被删除文件的文件名 * @return 单个文件删除成功返回true,不然返回false */ public static boolean deleteFile(String sPath) throws Exception { File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); } return true; } /** * 判断文件是否存在 * @param sPath 文件全路径 * @return * @throws Exception */ public static boolean fileIsExists(String sPath) throws Exception { File file = new File(sPath); return file.isFile() && file.exists(); } /** * 建立文件夹路径 * (给定全路径,该方法逐级建立文件夹) * @param sPath * 文件夹路径 * @return 建立成功返回true,不然返回false */ public static boolean creatFolder(String sPath) throws Exception { File firstFolder; String[] pathArr = sPath.split("/"); String checkPath = ""; for(String subPath : pathArr){ checkPath += subPath + "\\"; firstFolder = new File(checkPath); if(!firstFolder.exists() && !firstFolder.isDirectory()) { System.out.println("//文件夹不存在" + checkPath); firstFolder.mkdir(); }else{ System.out.println("//文件夹存在" + checkPath); } } return true; } /** * 将文件内容解析位字符串 * @param storePath 文件路径 * @return 内容 * @throws Exception */ public static String readContentFromDisk(String storePath) throws Exception{ StringBuffer content = new StringBuffer(); File file = new File(storePath); BufferedReader reader; try { reader = new BufferedReader(new FileReader(file)); String line = null; while((line = reader.readLine()) != null){ content.append(line); } } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content.toString(); } /** * 将内容写入文件 * @param storePath 文件路径 * @param content 写入内容 * @return 执行结果 */ public static boolean wirteContentToDisk(String storePath, String content) { BufferedWriter writer = null; FileWriter fileWriter = null; File file = null; try { file = new File(storePath); fileWriter = new FileWriter(file); writer = new BufferedWriter(fileWriter); writer.write(content); writer.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (fileWriter != null) { fileWriter.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } return true; } }