工程作完了,總結下用到的文件操做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; } }