JAVA文件操作工具类

开发 开发工具
博主发表的文章,有的是自己原创,有的是这些年本人从网上积累的,方便大家学习。

[[178775]]

  1. package com.rte.util; 
  2. import org.apache.tools.ant.Project; 
  3. import org.apache.tools.ant.taskdefs.Zip; 
  4. import org.apache.tools.ant.types.FileSet; 
  5. import java.io.*; 
  6. import java.nio.channels.FileChannel; 
  7. import java.text.DateFormat; 
  8. import java.text.MessageFormat; 
  9. import java.util.*; 
  10. import java.util.zip.ZipEntry; 
  11. import java.util.zip.ZipFile; 
  12. /** 
  13.  * 文件操作工具类 
  14.  * Created by zyb on 16/1/8. 
  15.  */ 
  16. public class FileUtil { 
  17.  /** 
  18.  * 创建目录 
  19.  * 
  20.  * @param dir 欲创建目录路径 
  21.  * @return 创建成功返回true,目录已存在或创建失败返回false 
  22.  */ 
  23.  public static boolean createDirectory(String dir) { 
  24.  File f = new File(dir); 
  25.  if (!f.exists()) { 
  26.  f.mkdirs(); 
  27.  return true
  28.  } 
  29.  return false
  30.  } 
  31.  /** 
  32.  * 创建文件 
  33.  * 
  34.  * @param fileDirectoryAndName 路径 
  35.  * @param fileContent 内容 
  36.  */ 
  37.  public static void createNewFile(String fileDirectoryAndName, String fileContent) { 
  38.  try { 
  39.  //创建File对象,参数为String类型,表示目录名 
  40.  File myFile = new File(fileDirectoryAndName); 
  41.  //判断文件是否存在,如果不存在则调用createNewFile()方法创建新目录,否则跳至异常处理代码 
  42.  if (!myFile.exists()) 
  43.  myFile.createNewFile(); 
  44.  else //如果不存在则扔出异常 
  45.  throw new Exception("The new file already exists!"); 
  46.  //下面把数据写入创建的文件 
  47.  write(fileContent, fileDirectoryAndName); 
  48.  } catch (Exception ex) { 
  49.  System.out.println("无法创建新文件!"); 
  50.  ex.printStackTrace(); 
  51.  } 
  52.  } 
  53.  /** 
  54.  * 保存信息到指定文件 
  55.  * 
  56.  * @param physicalPath 保存文件物理路径 
  57.  * @param inputStream 目标文件的输入流 
  58.  * @return 保存成功返回true,反之返回false 
  59.  */ 
  60.  public static boolean saveFileByPhysicalDir(String physicalPath, InputStream inputStream) { 
  61.  boolean flag = false
  62.  try { 
  63.  OutputStream os = new FileOutputStream(physicalPath); 
  64.  int readBytes = 0; 
  65.  byte buffer[] = new byte[8192]; 
  66.  while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) { 
  67.  os.write(buffer, 0, readBytes); 
  68.  } 
  69.  os.close(); 
  70.  flag = true
  71.  } catch (FileNotFoundException e) { 
  72.  e.printStackTrace(); 
  73.  } catch (IOException e) { 
  74.  e.printStackTrace(); 
  75.  } 
  76.  return flag; 
  77.  } 
  78.  /** 
  79.  * 保存字符串到指定路径 
  80.  * 
  81.  * @param physicalPath 保存物理路径 
  82.  * @param content 欲保存的字符串 
  83.  */ 
  84.  public static void saveAsFileOutputStream(String physicalPath, String content) { 
  85.  File file = new File(physicalPath); 
  86.  boolean b = file.getParentFile().isDirectory(); 
  87.  if (!b) { 
  88.  File tem = new File(file.getParent()); 
  89.  tem.mkdirs();// 创建目录 
  90.  } 
  91.  FileOutputStream foutput = null
  92.  try { 
  93.  foutput = new FileOutputStream(physicalPath); 
  94.  foutput.write(content.getBytes("UTF-8")); 
  95.  } catch (IOException ex) { 
  96.  ex.printStackTrace(); 
  97.  throw new RuntimeException(ex); 
  98.  } finally { 
  99.  try { 
  100.  foutput.flush(); 
  101.  foutput.close(); 
  102.  } catch (IOException ex) { 
  103.  ex.printStackTrace(); 
  104.  throw new RuntimeException(ex); 
  105.  } 
  106.  } 
  107.  } 
  108.  /** 
  109.  * 向文件添加信息(不会覆盖原文件内容) 
  110.  * 
  111.  * @param tivoliMsg 要写入的信息 
  112.  * @param logFileName 目标文件 
  113.  */ 
  114.  public static void write(String tivoliMsg, String logFileName) { 
  115.  try { 
  116.  byte[] bMsg = tivoliMsg.getBytes("UTF-8"); 
  117.  FileOutputStream fOut = new FileOutputStream(logFileName, true); 
  118.  fOut.write(bMsg); 
  119.  fOut.close(); 
  120.  } catch (IOException e) { 
  121.  } 
  122.  } 
  123.  /** 
  124.  * 日志写入 
  125.  * 例如: 
  126.  * 2016/01/08 17:46:42 : 001 : 这是一个日志输出。 
  127.  * 2016/01/08 17:46:55 : 001 : 这是一个日志输出。 
  128.  * 
  129.  * @param logFile 日志文件 
  130.  * @param batchId 处理编号 
  131.  * @param exceptionInfo 异常信息 
  132.  */ 
  133.  public static void writeLog(String logFile, String batchId, String exceptionInfo) { 
  134.  DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE); 
  135.  Object args[] = {df.format(new Date()), batchId, exceptionInfo}; 
  136.  String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args); 
  137.  try { 
  138.  File logfile = new File(logFile); 
  139.  if (!logfile.exists()) { 
  140.  logfile.createNewFile(); 
  141.  } 
  142.  FileWriter fw = new FileWriter(logFile, true); 
  143.  fw.write(fmtMsg); 
  144.  fw.write(System.getProperty("line.separator")); 
  145.  fw.flush(); 
  146.  fw.close(); 
  147.  } catch (Exception e) { 
  148.  } 
  149.  } 
  150.  /** 
  151.  * 读取文件信息 
  152.  * 
  153.  * @param realPath 目标文件 
  154.  * @return 文件内容 
  155.  */ 
  156.  public static String readTextFile(String realPath) throws Exception { 
  157.  File file = new File(realPath); 
  158.  if (!file.exists()) { 
  159.  System.out.println("File not exist!"); 
  160.  return null
  161.  } 
  162.  BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "UTF-8")); 
  163.  String temp = ""
  164.  String txt = ""
  165.  while ((temp = br.readLine()) != null) { 
  166.  txt += temp
  167.  } 
  168.  br.close(); 
  169.  return txt; 
  170.  } 
  171.  /** 
  172.  * 复制文件 
  173.  * 
  174.  * @param srcFile 源文件路径 
  175.  * @param targetFile 目标文件路径 
  176.  */ 
  177.  public static void copyFile(String srcFile, String targetFile) throws IOException { 
  178.  File scrfile = new File(srcFile); 
  179.  if (checkExist(srcFile)) { 
  180.  FileInputStream fi = null
  181.  FileOutputStream fo = null
  182.  FileChannel in = null
  183.  FileChannel out = null
  184.  try { 
  185.  fi = new FileInputStream(srcFile); 
  186.  fo = new FileOutputStream(targetFile); 
  187.  in = fi.getChannel(); 
  188.  out = fo.getChannel(); 
  189.  in.transferTo(0, in.size(), out); 
  190.  } catch (IOException e) { 
  191.  e.printStackTrace(); 
  192.  } finally { 
  193.  try { 
  194.  fi.close(); 
  195.  in.close(); 
  196.  fo.close(); 
  197.  out.close(); 
  198.  } catch (IOException e) { 
  199.  e.printStackTrace(); 
  200.  } 
  201.  } 
  202.  } 
  203.  } 
  204.  /** 
  205.  * 复制文件夹 
  206.  * 
  207.  * @param sourceDir String 源文件夹 
  208.  * @param destDir String 目标路径 
  209.  */ 
  210.  public static void copyDir(String sourceDir, String destDir) { 
  211.  File sourceFile = new File(sourceDir); 
  212.  String tempSource; 
  213.  String tempDest; 
  214.  String fileName; 
  215.  if (new File(destDir).getParentFile().isDirectory()) { 
  216.  new File(destDir).mkdirs(); 
  217.  } 
  218.  File[] files = sourceFile.listFiles(); 
  219.  for (int i = 0; i < files.length; i++) { 
  220.  fileName = files[i].getName(); 
  221.  tempSource = sourceDir + "/" + fileName; 
  222.  tempDest = destDir + "/" + fileName; 
  223.  if (files[i].isFile()) { 
  224.  try { 
  225.  copyFile(tempSource, tempDest); 
  226.  } catch (IOException e) { 
  227.  e.printStackTrace(); 
  228.  } 
  229.  } else { 
  230.  copyDir(tempSource, tempDest); 
  231.  } 
  232.  } 
  233.  sourceFile = null
  234.  } 
  235.  /** 
  236.  * 移动(重命名)文件 
  237.  * 
  238.  * @param srcFile 源文件路径 
  239.  * @param targetFile 目标文件路径 
  240.  */ 
  241.  public static void renameFile(String srcFile, String targetFile) throws IOException { 
  242.  try { 
  243.  copyFile(srcFile, targetFile); 
  244.  deleteFromName(srcFile); 
  245.  } catch (IOException e) { 
  246.  throw e; 
  247.  } 
  248.  } 
  249.  /** 
  250.  * 判断文件是否存在 
  251.  * 
  252.  * @param sFileName 文件路径 
  253.  * @return true - 存在、false - 不存在 
  254.  */ 
  255.  public static boolean checkExist(String sFileName) { 
  256.  boolean result = false
  257.  try { 
  258.  File f = new File(sFileName); 
  259.  if (f.exists() && f.isFile()) { 
  260.  result = true
  261.  } else { 
  262.  result = false
  263.  } 
  264.  } catch (Exception e) { 
  265.  result = false
  266.  } 
  267.  return result; 
  268.  } 
  269.  /** 
  270.  * 得到文件大小 
  271.  * 
  272.  * @param sFileName 文件路径 
  273.  * @return 文件大小(单位byte),文件不存在返回0,异常返回-1 
  274.  */ 
  275.  public static long getSize(String sFileName) { 
  276.  long lSize = 0; 
  277.  try { 
  278.  File f = new File(sFileName); 
  279.  if (f.exists()) { 
  280.  if (f.isFile() && f.canRead()) { 
  281.  lSize = f.length(); 
  282.  } else { 
  283.  lSize = -1; 
  284.  } 
  285.  } else { 
  286.  lSize = 0; 
  287.  } 
  288.  } catch (Exception e) { 
  289.  lSize = -1; 
  290.  } 
  291.  return lSize; 
  292.  } 
  293.  /** 
  294.  * 删除文件 
  295.  * 
  296.  * @param sFileName 文件路径 
  297.  * @return 成功返回true,反之返回false 
  298.  */ 
  299.  public static boolean deleteFromName(String sFileName) { 
  300.  boolean bReturn = true
  301.  try { 
  302.  File oFile = new File(sFileName); 
  303.  if (oFile.exists()) { 
  304.  boolean bResult = oFile.delete(); 
  305.  if (bResult == false) { 
  306.  bReturn = false
  307.  } 
  308.  } else { 
  309.  bReturn = false
  310.  } 
  311.  } catch (Exception e) { 
  312.  bReturn = false
  313.  } 
  314.  return bReturn; 
  315.  } 
  316.  /** 
  317.  * 删除指定目录及其中的所有内容。 
  318.  * 
  319.  * @param dir 要删除的目录 
  320.  * @return 删除成功时返回true,否则返回false。 
  321.  */ 
  322.  public static boolean deleteDirectory(File dir) { 
  323.  if (!dir.exists()) { 
  324.  return false
  325.  } 
  326.  File[] entries = dir.listFiles(); 
  327.  for (int i = 0; i < entries.length; i++) { 
  328.  if (entries[i].isDirectory()) { 
  329.  if (!deleteDirectory(entries[i])) { 
  330.  return false
  331.  } 
  332.  } else { 
  333.  if (!entries[i].delete()) { 
  334.  return false
  335.  } 
  336.  } 
  337.  } 
  338.  if (!dir.delete()) { 
  339.  return false
  340.  } 
  341.  return true
  342.  } 
  343.  /** 
  344.  * 解压缩 
  345.  * 
  346.  * @param sToPath 解压后路径 (为null或空时解压到源压缩文件路径) 
  347.  * @param sZipFile 压缩文件路径 
  348.  */ 
  349.  public static void unZip(String sToPath, String sZipFile) throws Exception { 
  350.  if (null == sToPath || ("").equals(sToPath.trim())) { 
  351.  File objZipFile = new File(sZipFile); 
  352.  sToPath = objZipFile.getParent(); 
  353.  } 
  354.  ZipFile zfile = new ZipFile(sZipFile); 
  355.  Enumeration zList = zfile.entries(); 
  356.  ZipEntry ze = null
  357.  byte[] buf = new byte[1024]; 
  358.  while (zList.hasMoreElements()) { 
  359.  ze = (ZipEntry) zList.nextElement(); 
  360.  if (ze.isDirectory()) { 
  361.  continue
  362.  } 
  363.  OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(sToPath, ze.getName()))); 
  364.  InputStream is = new BufferedInputStream(zfile.getInputStream(ze)); 
  365.  int readLen = 0; 
  366.  while ((readLen = is.read(buf, 0, 1024)) != -1) { 
  367.  os.write(buf, 0, readLen); 
  368.  } 
  369.  is.close(); 
  370.  os.close(); 
  371.  } 
  372.  zfile.close(); 
  373.  } 
  374.  /** 
  375.  * getRealFileName 
  376.  * 
  377.  * @param baseDir Root Directory 
  378.  * @param absFileName absolute Directory File Name 
  379.  * @return java.io.File Return file 
  380.  */ 
  381.  private static File getRealFileName(String baseDir, String absFileName) throws Exception { 
  382.  File ret = null
  383.  List dirs = new ArrayList(); 
  384.  StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator")); 
  385.  while (st.hasMoreTokens()) { 
  386.  dirs.add(st.nextToken()); 
  387.  } 
  388.  ret = new File(baseDir); 
  389.  if (dirs.size() > 1) { 
  390.  for (int i = 0; i < dirs.size() - 1; i++) { 
  391.  ret = new File(ret, (String) dirs.get(i)); 
  392.  } 
  393.  } 
  394.  if (!ret.exists()) { 
  395.  ret.mkdirs(); 
  396.  } 
  397.  ret = new File(ret, (String) dirs.get(dirs.size() - 1)); 
  398.  return ret; 
  399.  } 
  400.  /** 
  401.  * 压缩文件夹 
  402.  * 
  403.  * @param srcPathName 欲压缩的文件夹 
  404.  * @param finalFile 压缩后的zip文件 (为null或“”时默认同欲压缩目录) 
  405.  * @param strIncludes 包括哪些文件或文件夹 eg:zip.setIncludes("*.java");(没有时可为null) 
  406.  * @param strExcludes 排除哪些文件或文件夹 (没有时可为null) 
  407.  */ 
  408.  public static void zip(String srcPathName, String finalFile, String strIncludes, String strExcludes) { 
  409.  File srcdir = new File(srcPathName); 
  410.  if (!srcdir.exists()) { 
  411.  throw new RuntimeException(srcPathName + "不存在!"); 
  412.  } 
  413.  if (finalFile == null || "".equals(finalFile)) { 
  414.  finalFile = srcPathName + ".zip"
  415.  } 
  416.  File zipFile = new File(finalFile); 
  417.  Project prj = new Project(); 
  418.  Zip zip = new Zip(); 
  419.  zip.setProject(prj); 
  420.  zip.setDestFile(zipFile); 
  421.  FileSet fileSet = new FileSet(); 
  422.  fileSet.setProject(prj); 
  423.  fileSet.setDir(srcdir); 
  424.  if (strIncludes != null && !"".equals(strIncludes)) { 
  425.  fileSet.setIncludes(strIncludes); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java"); 
  426.  } 
  427.  if (strExcludes != null && !"".equals(strExcludes)) { 
  428.  fileSet.setExcludes(strExcludes); //排除哪些文件或文件夹 
  429.  } 
  430.  zip.addFileset(fileSet); 
  431.  zip.execute(); 
  432.  } 

 【本文是51CTO专栏作者张勇波的原创文章,转载请通过51CTO获取作者授权】

责任编辑:武晓燕 来源: 上下求索的Z先生博客
相关推荐

2016-12-13 10:59:59

日期操作工具

2010-07-26 09:14:54

SQL Server

2010-02-25 13:34:24

Linux磁盘分区

2022-12-19 07:21:35

Hutool-db数据库JDBC

2011-12-11 18:37:18

iPad

2011-11-30 16:39:33

50种网络协作工具

2009-01-04 11:55:09

Java数组Java常用工具Java类

2009-06-17 16:12:26

java电子书制作软件

2020-06-27 09:01:53

Java包装类编程语言

2011-11-22 09:27:45

Java开源工具

2020-07-08 07:56:08

Java工具类包装类

2021-11-20 22:20:10

Windows 11Windows微软

2022-05-09 11:54:50

电信巨头T-Mobile网络攻击

2023-11-02 08:56:59

ORMGORM

2012-05-23 15:11:56

Windows Pho

2013-10-28 13:05:38

Mozilla工具

2020-02-10 12:38:30

远程办公

2020-06-05 14:29:07

PythonPandas数据分析

2020-06-29 07:52:17

Java工具类开发

2010-09-14 17:20:30

点赞
收藏

51CTO技术栈公众号