JAVA文件操作工具類
作者:張勇波
博主發(fā)表的文章,有的是自己原創(chuàng),有的是這些年本人從網(wǎng)上積累的,方便大家學(xué)習(xí)。
- package com.rte.util;
- import org.apache.tools.ant.Project;
- import org.apache.tools.ant.taskdefs.Zip;
- import org.apache.tools.ant.types.FileSet;
- import java.io.*;
- import java.nio.channels.FileChannel;
- import java.text.DateFormat;
- import java.text.MessageFormat;
- import java.util.*;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipFile;
- /**
- * 文件操作工具類
- * Created by zyb on 16/1/8.
- */
- public class FileUtil {
- /**
- * 創(chuàng)建目錄
- *
- * @param dir 欲創(chuàng)建目錄路徑
- * @return 創(chuàng)建成功返回true,目錄已存在或創(chuàng)建失敗返回false
- */
- public static boolean createDirectory(String dir) {
- File f = new File(dir);
- if (!f.exists()) {
- f.mkdirs();
- return true;
- }
- return false;
- }
- /**
- * 創(chuàng)建文件
- *
- * @param fileDirectoryAndName 路徑
- * @param fileContent 內(nèi)容
- */
- public static void createNewFile(String fileDirectoryAndName, String fileContent) {
- try {
- //創(chuàng)建File對(duì)象,參數(shù)為String類型,表示目錄名
- File myFile = new File(fileDirectoryAndName);
- //判斷文件是否存在,如果不存在則調(diào)用createNewFile()方法創(chuàng)建新目錄,否則跳至異常處理代碼
- if (!myFile.exists())
- myFile.createNewFile();
- else //如果不存在則扔出異常
- throw new Exception("The new file already exists!");
- //下面把數(shù)據(jù)寫(xiě)入創(chuàng)建的文件
- write(fileContent, fileDirectoryAndName);
- } catch (Exception ex) {
- System.out.println("無(wú)法創(chuàng)建新文件!");
- ex.printStackTrace();
- }
- }
- /**
- * 保存信息到指定文件
- *
- * @param physicalPath 保存文件物理路徑
- * @param inputStream 目標(biāo)文件的輸入流
- * @return 保存成功返回true,反之返回false
- */
- public static boolean saveFileByPhysicalDir(String physicalPath, InputStream inputStream) {
- boolean flag = false;
- try {
- OutputStream os = new FileOutputStream(physicalPath);
- int readBytes = 0;
- byte buffer[] = new byte[8192];
- while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
- os.write(buffer, 0, readBytes);
- }
- os.close();
- flag = true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return flag;
- }
- /**
- * 保存字符串到指定路徑
- *
- * @param physicalPath 保存物理路徑
- * @param content 欲保存的字符串
- */
- public static void saveAsFileOutputStream(String physicalPath, String content) {
- File file = new File(physicalPath);
- boolean b = file.getParentFile().isDirectory();
- if (!b) {
- File tem = new File(file.getParent());
- tem.mkdirs();// 創(chuàng)建目錄
- }
- FileOutputStream foutput = null;
- try {
- foutput = new FileOutputStream(physicalPath);
- foutput.write(content.getBytes("UTF-8"));
- } catch (IOException ex) {
- ex.printStackTrace();
- throw new RuntimeException(ex);
- } finally {
- try {
- foutput.flush();
- foutput.close();
- } catch (IOException ex) {
- ex.printStackTrace();
- throw new RuntimeException(ex);
- }
- }
- }
- /**
- * 向文件添加信息(不會(huì)覆蓋原文件內(nèi)容)
- *
- * @param tivoliMsg 要寫(xiě)入的信息
- * @param logFileName 目標(biāo)文件
- */
- public static void write(String tivoliMsg, String logFileName) {
- try {
- byte[] bMsg = tivoliMsg.getBytes("UTF-8");
- FileOutputStream fOut = new FileOutputStream(logFileName, true);
- fOut.write(bMsg);
- fOut.close();
- } catch (IOException e) {
- }
- }
- /**
- * 日志寫(xiě)入
- * 例如:
- * 2016/01/08 17:46:42 : 001 : 這是一個(gè)日志輸出。
- * 2016/01/08 17:46:55 : 001 : 這是一個(gè)日志輸出。
- *
- * @param logFile 日志文件
- * @param batchId 處理編號(hào)
- * @param exceptionInfo 異常信息
- */
- public static void writeLog(String logFile, String batchId, String exceptionInfo) {
- DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);
- Object args[] = {df.format(new Date()), batchId, exceptionInfo};
- String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);
- try {
- File logfile = new File(logFile);
- if (!logfile.exists()) {
- logfile.createNewFile();
- }
- FileWriter fw = new FileWriter(logFile, true);
- fw.write(fmtMsg);
- fw.write(System.getProperty("line.separator"));
- fw.flush();
- fw.close();
- } catch (Exception e) {
- }
- }
- /**
- * 讀取文件信息
- *
- * @param realPath 目標(biāo)文件
- * @return 文件內(nèi)容
- */
- public static String readTextFile(String realPath) throws Exception {
- File file = new File(realPath);
- if (!file.exists()) {
- System.out.println("File not exist!");
- return null;
- }
- BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "UTF-8"));
- String temp = "";
- String txt = "";
- while ((temp = br.readLine()) != null) {
- txt += temp;
- }
- br.close();
- return txt;
- }
- /**
- * 復(fù)制文件
- *
- * @param srcFile 源文件路徑
- * @param targetFile 目標(biāo)文件路徑
- */
- public static void copyFile(String srcFile, String targetFile) throws IOException {
- File scrfile = new File(srcFile);
- if (checkExist(srcFile)) {
- FileInputStream fi = null;
- FileOutputStream fo = null;
- FileChannel in = null;
- FileChannel out = null;
- try {
- fi = new FileInputStream(srcFile);
- fo = new FileOutputStream(targetFile);
- in = fi.getChannel();
- out = fo.getChannel();
- in.transferTo(0, in.size(), out);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- fi.close();
- in.close();
- fo.close();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * 復(fù)制文件夾
- *
- * @param sourceDir String 源文件夾
- * @param destDir String 目標(biāo)路徑
- */
- public static void copyDir(String sourceDir, String destDir) {
- File sourceFile = new File(sourceDir);
- String tempSource;
- String tempDest;
- String fileName;
- if (new File(destDir).getParentFile().isDirectory()) {
- new File(destDir).mkdirs();
- }
- File[] files = sourceFile.listFiles();
- for (int i = 0; i < files.length; i++) {
- fileName = files[i].getName();
- tempSource = sourceDir + "/" + fileName;
- tempDest = destDir + "/" + fileName;
- if (files[i].isFile()) {
- try {
- copyFile(tempSource, tempDest);
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- copyDir(tempSource, tempDest);
- }
- }
- sourceFile = null;
- }
- /**
- * 移動(dòng)(重命名)文件
- *
- * @param srcFile 源文件路徑
- * @param targetFile 目標(biāo)文件路徑
- */
- public static void renameFile(String srcFile, String targetFile) throws IOException {
- try {
- copyFile(srcFile, targetFile);
- deleteFromName(srcFile);
- } catch (IOException e) {
- throw e;
- }
- }
- /**
- * 判斷文件是否存在
- *
- * @param sFileName 文件路徑
- * @return true - 存在、false - 不存在
- */
- public static boolean checkExist(String sFileName) {
- boolean result = false;
- try {
- File f = new File(sFileName);
- if (f.exists() && f.isFile()) {
- result = true;
- } else {
- result = false;
- }
- } catch (Exception e) {
- result = false;
- }
- return result;
- }
- /**
- * 得到文件大小
- *
- * @param sFileName 文件路徑
- * @return 文件大?。▎挝籦yte),文件不存在返回0,異常返回-1
- */
- public static long getSize(String sFileName) {
- long lSize = 0;
- try {
- File f = new File(sFileName);
- if (f.exists()) {
- if (f.isFile() && f.canRead()) {
- lSize = f.length();
- } else {
- lSize = -1;
- }
- } else {
- lSize = 0;
- }
- } catch (Exception e) {
- lSize = -1;
- }
- return lSize;
- }
- /**
- * 刪除文件
- *
- * @param sFileName 文件路徑
- * @return 成功返回true,反之返回false
- */
- public static boolean deleteFromName(String sFileName) {
- boolean bReturn = true;
- try {
- File oFile = new File(sFileName);
- if (oFile.exists()) {
- boolean bResult = oFile.delete();
- if (bResult == false) {
- bReturn = false;
- }
- } else {
- bReturn = false;
- }
- } catch (Exception e) {
- bReturn = false;
- }
- return bReturn;
- }
- /**
- * 刪除指定目錄及其中的所有內(nèi)容。
- *
- * @param dir 要?jiǎng)h除的目錄
- * @return 刪除成功時(shí)返回true,否則返回false。
- */
- public static boolean deleteDirectory(File dir) {
- if (!dir.exists()) {
- return false;
- }
- File[] entries = dir.listFiles();
- for (int i = 0; i < entries.length; i++) {
- if (entries[i].isDirectory()) {
- if (!deleteDirectory(entries[i])) {
- return false;
- }
- } else {
- if (!entries[i].delete()) {
- return false;
- }
- }
- }
- if (!dir.delete()) {
- return false;
- }
- return true;
- }
- /**
- * 解壓縮
- *
- * @param sToPath 解壓后路徑 (為null或空時(shí)解壓到源壓縮文件路徑)
- * @param sZipFile 壓縮文件路徑
- */
- public static void unZip(String sToPath, String sZipFile) throws Exception {
- if (null == sToPath || ("").equals(sToPath.trim())) {
- File objZipFile = new File(sZipFile);
- sToPath = objZipFile.getParent();
- }
- ZipFile zfile = new ZipFile(sZipFile);
- Enumeration zList = zfile.entries();
- ZipEntry ze = null;
- byte[] buf = new byte[1024];
- while (zList.hasMoreElements()) {
- ze = (ZipEntry) zList.nextElement();
- if (ze.isDirectory()) {
- continue;
- }
- OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(sToPath, ze.getName())));
- InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
- int readLen = 0;
- while ((readLen = is.read(buf, 0, 1024)) != -1) {
- os.write(buf, 0, readLen);
- }
- is.close();
- os.close();
- }
- zfile.close();
- }
- /**
- * getRealFileName
- *
- * @param baseDir Root Directory
- * @param absFileName absolute Directory File Name
- * @return java.io.File Return file
- */
- private static File getRealFileName(String baseDir, String absFileName) throws Exception {
- File ret = null;
- List dirs = new ArrayList();
- StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));
- while (st.hasMoreTokens()) {
- dirs.add(st.nextToken());
- }
- ret = new File(baseDir);
- if (dirs.size() > 1) {
- for (int i = 0; i < dirs.size() - 1; i++) {
- ret = new File(ret, (String) dirs.get(i));
- }
- }
- if (!ret.exists()) {
- ret.mkdirs();
- }
- ret = new File(ret, (String) dirs.get(dirs.size() - 1));
- return ret;
- }
- /**
- * 壓縮文件夾
- *
- * @param srcPathName 欲壓縮的文件夾
- * @param finalFile 壓縮后的zip文件 (為null或“”時(shí)默認(rèn)同欲壓縮目錄)
- * @param strIncludes 包括哪些文件或文件夾 eg:zip.setIncludes("*.java");(沒(méi)有時(shí)可為null)
- * @param strExcludes 排除哪些文件或文件夾 (沒(méi)有時(shí)可為null)
- */
- public static void zip(String srcPathName, String finalFile, String strIncludes, String strExcludes) {
- File srcdir = new File(srcPathName);
- if (!srcdir.exists()) {
- throw new RuntimeException(srcPathName + "不存在!");
- }
- if (finalFile == null || "".equals(finalFile)) {
- finalFile = srcPathName + ".zip";
- }
- File zipFile = new File(finalFile);
- Project prj = new Project();
- Zip zip = new Zip();
- zip.setProject(prj);
- zip.setDestFile(zipFile);
- FileSet fileSet = new FileSet();
- fileSet.setProject(prj);
- fileSet.setDir(srcdir);
- if (strIncludes != null && !"".equals(strIncludes)) {
- fileSet.setIncludes(strIncludes); //包括哪些文件或文件夾 eg:zip.setIncludes("*.java");
- }
- if (strExcludes != null && !"".equals(strExcludes)) {
- fileSet.setExcludes(strExcludes); //排除哪些文件或文件夾
- }
- zip.addFileset(fileSet);
- zip.execute();
- }
- }
【本文是51CTO專欄作者張勇波的原創(chuàng)文章,轉(zhuǎn)載請(qǐng)通過(guò)51CTO獲取作者授權(quán)】
責(zé)任編輯:武曉燕
來(lái)源:
上下求索的Z先生博客