热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

java文件处理工具类详解

这篇文章主要为大家详细介绍了java文件处理工具类的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java文件处理工具类的具体代码,供大家参考,具体内容如下

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtil
{
 private static Log logger = LogFactory.getLog(FileUtil.class);
 
 public static void writeFile(String paramString1, String paramString2)
 {
  writeFile(paramString1, paramString2, "utf-8");
 }
 
 public static void writeFile(String paramString1, String paramString2, String paramString3)
 {
  try
  {
   createFolder(paramString1, true);
   BufferedWriter localBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(paramString1), paramString3));
   localBufferedWriter.write(paramString2);
   localBufferedWriter.close();
  }
  catch (IOException localIOException)
  {
   localIOException.printStackTrace();
  }
 }
 
 public static void writeFile(String paramString, InputStream paramInputStream)
  throws IOException
 {
  FileOutputStream localFileOutputStream = new FileOutputStream(paramString);
  byte[] arrayOfByte = new byte['Ȁ'];
  int i = 0;
  while ((i = paramInputStream.read(arrayOfByte)) != -1) {
   localFileOutputStream.write(arrayOfByte, 0, i);
  }
  paramInputStream.close();
  localFileOutputStream.close();
 }
 
 public static String readFile(String paramString)
  throws IOException
 {
  try
  {
   File localFile = new File(paramString);
   String str1 = getCharset(localFile);
   StringBuffer localStringBuffer = new StringBuffer();
   BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(paramString), str1));
   String str2;
   while ((str2 = localBufferedReader.readLine()) != null) {
    localStringBuffer.append(str2 + "\r\n");
   }
   localBufferedReader.close();
   return localStringBuffer.toString();
  }
  catch (IOException localIOException)
  {
   throw localIOException;
  }
 }
 
 public static boolean isExistFile(String paramString)
 {
  boolean bool = false;
  File localFile = new File(paramString);
  if (localFile.isDirectory())
  {
   File[] arrayOfFile = localFile.listFiles();
   if ((arrayOfFile != null) && (arrayOfFile.length != 0)) {
    bool = true;
   }
  }
  return bool;
 }
 
 public static String getCharset(File paramFile)
 {
  String str = "GBK";
  byte[] arrayOfByte = new byte[3];
  try
  {
   int i = 0;
   BufferedInputStream localBufferedInputStream = new BufferedInputStream(new FileInputStream(paramFile));
   localBufferedInputStream.mark(0);
   int j = localBufferedInputStream.read(arrayOfByte, 0, 3);
   if (j == -1) {
    return str;
   }
   if ((arrayOfByte[0] == -1) && (arrayOfByte[1] == -2))
   {
    str = "UTF-16LE";
    i = 1;
   }
   else if ((arrayOfByte[0] == -2) && (arrayOfByte[1] == -1))
   {
    str = "UTF-16BE";
    i = 1;
   }
   else if ((arrayOfByte[0] == -17) && (arrayOfByte[1] == -69) && (arrayOfByte[2] == -65))
   {
    str = "UTF-8";
    i = 1;
   }
   localBufferedInputStream.reset();
   if (i == 0)
   {
    int k = 0;
    while ((j = localBufferedInputStream.read()) != -1)
    {
     k++;
     if ((j <240) && ((128 > j) || (j > 191))) {
      if ((192 <= j) && (j <= 223))
      {
       j = localBufferedInputStream.read();
       if (128 > j) {
        break;
       }
       if (j > 191) {
        break;
       }
      }
      else if ((224 <= j) && (j <= 239))
      {
       j = localBufferedInputStream.read();
       if ((128 <= j) && (j <= 191))
       {
        j = localBufferedInputStream.read();
        if ((128 <= j) && (j <= 191)) {
         str = "UTF-8";
        }
       }
      }
     }
    }
   }
   localBufferedInputStream.close();
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
  }
  return str;
 }
 
 public static byte[] readByte(InputStream paramInputStream)
 {
  try
  {
   byte[] arrayOfByte = new byte[paramInputStream.available()];
   paramInputStream.read(arrayOfByte);
   return arrayOfByte;
  }
  catch (FileNotFoundException localFileNotFoundException)
  {
   logger.error("文件路径不存在:" + localFileNotFoundException.getMessage());
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
  }
  return null;
 }
 
 public static byte[] readByte(String paramString)
 {
  try
  {
   FileInputStream localFileInputStream = new FileInputStream(paramString);
   byte[] arrayOfByte = new byte[localFileInputStream.available()];
   localFileInputStream.read(arrayOfByte);
   localFileInputStream.close();
   return arrayOfByte;
  }
  catch (FileNotFoundException localFileNotFoundException)
  {
   logger.error("文件路径不存在:" + paramString);
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
  }
  return null;
 }
 
 public static boolean writeByte(String paramString, byte[] paramArrayOfByte)
 {
  try
  {
   BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(new FileOutputStream(paramString));
   localBufferedOutputStream.write(paramArrayOfByte);
   localBufferedOutputStream.close();
   return true;
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
  }
  return false;
 }
 
 public static boolean deleteDir(File paramFile)
 {
  if (paramFile.isDirectory())
  {
   String[] arrayOfString = paramFile.list();
   for (int i = 0; i  getDiretoryOnly(File paramFile)
 {
  ArrayList localArrayList = new ArrayList();
  if ((paramFile != null) && (paramFile.exists()) && (paramFile.isDirectory()))
  {
   File[] arrayOfFile = paramFile.listFiles(new FileFilter()
   {
    public boolean accept(File paramAnonymousFile)
    {
     return paramAnonymousFile.isDirectory();
    }
   });
   for (int i = 0; i  getFileOnly(File paramFile)
 {
  ArrayList localArrayList = new ArrayList();
  File[] arrayOfFile = paramFile.listFiles(new FileFilter()
  {
   public boolean accept(File paramAnonymousFile)
   {
    return paramAnonymousFile.isFile();
   }
  });
  for (int i = 0; i  -1) {
   return paramString.substring(i + 1).toLowerCase();
  }
  return "";
 }
 
 public static void copyDir(String paramString1, String paramString2)
  throws IOException
 {
  new File(paramString2).mkdirs();
  File[] arrayOfFile = new File(paramString1).listFiles();
  for (int i = 0; i  1048576.0D)
  {
   d = paramDouble / 1048576.0D;
   return localDecimalFormat.format(d) + " M";
  }
  if (paramDouble > 1024.0D)
  {
   d = paramDouble / 1024.0D;
   return localDecimalFormat.format(d) + " KB";
  }
  return paramDouble + " bytes";
 }
 
 public static void downLoadFile(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString1, String paramString2)
  throws IOException
 {
  ServletOutputStream localServletOutputStream = paramHttpServletResponse.getOutputStream();
  File localFile = new File(paramString1);
  if (localFile.exists())
  {
   paramHttpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
   String str1 = getFileExt(paramString1);
   if ((!Validation.isEmpty(str1)) && (str1.toLowerCase().equals("apk"))) {
    paramHttpServletResponse.setContentType("application/vnd.android.package-archive");
   }
   String str2 = paramString2;
   String str3 = paramHttpServletRequest.getHeader("USER-AGENT");
   if ((str3 != null) && (str3.indexOf("MSIE") == -1))
   {
    try
    {
     String localObject1 = transCharacter(paramHttpServletRequest, str2);
     paramHttpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + (String)localObject1);
    }
    catch (Exception localException1)
    {
     localException1.printStackTrace();
    }
   }
   else
   {
    str2 = URLEncoder.encode(str2, "utf-8");
    paramHttpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + str2);
   }
   Object localObject1 = null;
   try
   {
    localServletOutputStream = paramHttpServletResponse.getOutputStream();
    localObject1 = new FileInputStream(paramString1);
    byte[] arrayOfByte = new byte['&#1024;'];
    int i = 0;
    while ((i = ((FileInputStream)localObject1).read(arrayOfByte)) > 0) {
     localServletOutputStream.write(arrayOfByte, 0, i);
    }
    localServletOutputStream.flush();
   }
   catch (Exception localException2)
   {
    localException2.printStackTrace();
   }
   finally
   {
    if (localObject1 != null)
    {
     ((FileInputStream)localObject1).close();
     localObject1 = null;
    }
    if (localServletOutputStream != null)
    {
     localServletOutputStream.close();
     localServletOutputStream = null;
     paramHttpServletResponse.flushBuffer();
    }
   }
  }
  else
  {
   localServletOutputStream.write("文件不存在!".getBytes("utf-8"));
  }
 }
 
 private static String transCharacter(HttpServletRequest paramHttpServletRequest, String paramString)
  throws Exception
 {
  if (paramHttpServletRequest.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0) {
   return URLEncoder.encode(paramString, "UTF-8");
  }
  if (paramHttpServletRequest.getHeader("USER-AGENT").toLowerCase().indexOf("firefox") > 0) {
   return new String(paramString.getBytes("UTF-8"), "ISO8859-1");
  }
  return new String(paramString.getBytes("gbk"), "ISO8859-1");
 }
 
 public static String getParentDir(String paramString1, String paramString2)
 {
  File localFile = new File(paramString2);
  String str1 = localFile.getParent();
  String str2 = str1.replace(paramString1, "");
  return str2.replace(File.separator, "/");
 }
 
 public static String getClassesPath()
 {
  String str = StringUtil.trimSufffix(AppUtil.getRealPath("/"), File.separator) + "\\WEB-INF\\classes\\".replace("\\", File.separator);
  return str;
 }
 
 public static String getRootPath()
 {
  String str = StringUtil.trimSufffix(AppUtil.getRealPath("/"), File.separator) + File.separator;
  return str;
 }
 
 public static String readFromProperties(String paramString1, String paramString2)
 {
  String str1 = "";
  BufferedInputStream localBufferedInputStream = null;
  try
  {
   localBufferedInputStream = new BufferedInputStream(new FileInputStream(paramString1));
   Properties localProperties = new Properties();
   localProperties.load(localBufferedInputStream);
   str1 = localProperties.getProperty(paramString2);
   String str2 = str1;
   return str2;
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
  }
  finally
  {
   if (localBufferedInputStream != null) {
    try
    {
     localBufferedInputStream.close();
    }
    catch (IOException localIOException3)
    {
     localIOException3.printStackTrace();
    }
   }
  }
  return str1;
 }
 
 public static boolean saveProperties(String paramString1, String paramString2, String paramString3)
 {
  StringBuffer localStringBuffer = new StringBuffer();
  int i = 0;
  BufferedReader localBufferedReader = null;
  try
  {
   localBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(paramString1), "utf-8"));
   String str;
   while ((str = localBufferedReader.readLine()) != null) {
    if (str.startsWith(paramString2))
    {
     localStringBuffer.append(paramString2 + "=" + paramString3 + "\r\n");
     i = 1;
    }
    else
    {
     localStringBuffer.append(str + "\r\n");
    }
   }
   if (i == 0) {
    localStringBuffer.append(paramString2 + "=" + paramString3 + "\r\n");
   }
   writeFile(paramString1, localStringBuffer.toString(), "utf-8");
   boolean bool1 = true;
   return bool1;
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
   boolean bool2 = false;
   return bool2;
  }
  finally
  {
   if (localBufferedReader != null) {
    try
    {
     localBufferedReader.close();
    }
    catch (IOException localIOException3)
    {
     localIOException3.printStackTrace();
    }
   }
  }
 }
 
 public static boolean delProperties(String paramString1, String paramString2)
 {
  StringBuffer localStringBuffer = new StringBuffer();
  BufferedReader localBufferedReader = null;
  try
  {
   localBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(paramString1), "utf-8"));
   String str;
   while ((str = localBufferedReader.readLine()) != null) {
    if (!str.startsWith(paramString2)) {
     localStringBuffer.append(str + "\r\n");
    }
   }
   writeFile(paramString1, localStringBuffer.toString(), "utf-8");
   boolean bool1 = true;
   return bool1;
  }
  catch (Exception localException)
  {
   localException.printStackTrace();
   boolean bool2 = false;
   return bool2;
  }
  finally
  {
   if (localBufferedReader != null) {
    try
    {
     localBufferedReader.close();
    }
    catch (IOException localIOException3)
    {
     localIOException3.printStackTrace();
    }
   }
  }
 }
 
 public static List> getAllClassesByInterface(Class<&#63;> paramClass, boolean paramBoolean)
  throws IOException, ClassNotFoundException, IllegalStateException
 {
  if (!paramClass.isInterface()) {
   throw new IllegalStateException("Class not a interface.");
  }
  ClassLoader localClassLoader = paramClass.getClassLoader();
  String str = paramBoolean &#63; paramClass.getPackage().getName() : "/";
  return findClasses(paramClass, localClassLoader, str);
 }
 
 private static List> findClasses(Class<&#63;> paramClass, ClassLoader paramClassLoader, String paramString)
  throws IOException, ClassNotFoundException
 {
  ArrayList localArrayList = new ArrayList();
  String str = paramString.replace(".", "/");
  Object localObject;
  if (!str.equals("/"))
  {
   localObject = paramClassLoader.getResources(str);
   while (((Enumeration)localObject).hasMoreElements())
   {
    URL localURL = (URL)((Enumeration)localObject).nextElement();
    localArrayList.addAll(findResources(paramClass, new File(localURL.getFile()), paramString));
   }
  }
  else
  {
   localObject = paramClassLoader.getResource("").getPath();
   localArrayList.addAll(findResources(paramClass, new File((String)localObject), paramString));
  }
  return localArrayList;
 }
 
 private static List> findResources(Class<&#63;> paramClass, File paramFile, String paramString)
  throws ClassNotFoundException
 {
  ArrayList localArrayList = new ArrayList();
  if (!paramFile.exists()) {
   return Collections.EMPTY_LIST;
  }
  File[] arrayOfFile1 = paramFile.listFiles();
  for (File localFile : arrayOfFile1) {
   if (localFile.isDirectory())
   {
    if (!localFile.getName().contains(".")) {
     if (!paramString.equals("/")) {
      localArrayList.addAll(findResources(paramClass, localFile, paramString + "." + localFile.getName()));
     } else {
      localArrayList.addAll(findResources(paramClass, localFile, localFile.getName()));
     }
    }
   }
   else if (localFile.getName().endsWith(".class"))
   {
    Class localClass = null;
    if (!paramString.equals("/")) {
     localClass = Class.forName(paramString + "." + localFile.getName().substring(0, localFile.getName().length() - 6));
    } else {
     localClass = Class.forName(localFile.getName().substring(0, localFile.getName().length() - 6));
    }
    if ((paramClass.isAssignableFrom(localClass)) && (!paramClass.equals(localClass))) {
     localArrayList.add(localClass);
    }
   }
  }
  return localArrayList;
 }
 
 public static Object cloneObject(Object paramObject)
  throws Exception
 {
  ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
  ObjectOutputStream localObjectOutputStream = new ObjectOutputStream(localByteArrayOutputStream);
  localObjectOutputStream.writeObject(paramObject);
  ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(localByteArrayOutputStream.toByteArray());
  ObjectInputStream localObjectInputStream = new ObjectInputStream(localByteArrayInputStream);
  return localObjectInputStream.readObject();
 }
 
 public static boolean isFileType(String paramString1, String paramString2)
 {
  boolean bool = false;
  if (("IMAGE".equals(paramString2)) && ((paramString1.toUpperCase().equals("JPG")) || (paramString1.toUpperCase().equals("PNG")) || (paramString1.toUpperCase().equals("GIF")) || (paramString1.toUpperCase().equals("JPEG")))) {
   bool = true;
  }
  return bool;
 }
 
 public static boolean isFileType(String paramString, String[] paramArrayOfString)
 {
  boolean bool = false;
  if ((paramArrayOfString != null) && (paramArrayOfString.length > 0)) {
   for (int i = 0; i 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 解决JAX-WS动态客户端工厂弃用问题并迁移到XFire
    在处理Java项目中的JAR包冲突时,我们遇到了JaxWsDynamicClientFactory被弃用的问题,并成功将其迁移到org.codehaus.xfire.client。本文详细介绍了这一过程及解决方案。 ... [详细]
  • 本文详细介绍如何使用arm-eabi-gdb调试Android平台上的C/C++程序。通过具体步骤和实用技巧,帮助开发者更高效地进行调试工作。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 如何在WPS Office for Mac中调整Word文档的文字排列方向
    本文将详细介绍如何使用最新版WPS Office for Mac调整Word文档中的文字排列方向。通过这些步骤,用户可以轻松更改文本的水平或垂直排列方式,以满足不同的排版需求。 ... [详细]
  • 本文总结了在使用Ionic 5进行Android平台APK打包时遇到的问题,特别是针对QRScanner插件的改造。通过详细分析和提供具体的解决方法,帮助开发者顺利打包并优化应用性能。 ... [详细]
  • XNA 3.0 游戏编程:从 XML 文件加载数据
    本文介绍如何在 XNA 3.0 游戏项目中从 XML 文件加载数据。我们将探讨如何将 XML 数据序列化为二进制文件,并通过内容管道加载到游戏中。此外,还会涉及自定义类型读取器和写入器的实现。 ... [详细]
  • UNP 第9章:主机名与地址转换
    本章探讨了用于在主机名和数值地址之间进行转换的函数,如gethostbyname和gethostbyaddr。此外,还介绍了getservbyname和getservbyport函数,用于在服务器名和端口号之间进行转换。 ... [详细]
  • 本文详细介绍了如何使用ActionScript 3.0 (AS3) 连接并操作MySQL数据库。通过具体的代码示例和步骤说明,帮助开发者理解并实现这一过程。 ... [详细]
  • 在即将迎来26岁生日之际,作者的人生陷入了低谷。经过近三年的硕士学习后,最终决定退学,并且面临没有工作经验的困境。尽管如此,作者依然坚定地选择为自己的人生负责。 ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • 本文介绍如何在Java项目中使用Log4j库进行日志记录。我们将详细说明Log4j库的引入、配置及简单应用,帮助开发者快速上手。 ... [详细]
  • 本文详细介绍了如何在ECharts中使用线性渐变色,通过echarts.graphic.LinearGradient方法实现。文章不仅提供了完整的代码示例,还解释了各个参数的具体含义及其应用场景。 ... [详细]
  • 探讨了小型企业在构建安全网络和软件时所面临的挑战和机遇。本文介绍了如何通过合理的方法和工具,确保小型企业能够有效提升其软件的安全性,从而保护客户数据并增强市场竞争力。 ... [详细]
author-avatar
mobiledu2502940393
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有