热门标签 | 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 

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


推荐阅读
  • HTTP(HyperTextTransferProtocol)是超文本传输协议的缩写,它用于传送www方式的数据。HTTP协议采用了请求响应模型。客服端向服务器发送一 ... [详细]
  • Visual Studio 2019 安装指南
    作为一名拥有三年经验的程序员,由于长期专注于C语言,我意识到自己的技术栈过于单一。在转型为Android驱动开发工程师后,这种局限性更加明显。本文将介绍如何安装Visual Studio 2019,并配置C++开发环境,以帮助读者拓宽技术视野。 ... [详细]
  • 本文介绍了如何使用Flume从Linux文件系统收集日志并存储到HDFS,然后通过MapReduce清洗数据,使用Hive进行数据分析,并最终通过Sqoop将结果导出到MySQL数据库。 ... [详细]
  • javax.mail.search.BodyTerm.matchPart()方法的使用及代码示例 ... [详细]
  • Spring 切面配置中的切点表达式详解
    本文介绍了如何在Spring框架中使用AspectJ风格的切面配置,详细解释了切点表达式的语法和常见示例,帮助开发者更好地理解和应用Spring AOP。 ... [详细]
  • 用阿里云的免费 SSL 证书让网站从 HTTP 换成 HTTPS
    HTTP协议是不加密传输数据的,也就是用户跟你的网站之间传递数据有可能在途中被截获,破解传递的真实内容,所以使用不加密的HTTP的网站是不 ... [详细]
  • 如何在服务器上配置SSL证书
    SSL证书是用于验证互联网上身份的一种数字凭证,通过启用HTTPS协议,确保用户与服务器之间的通信安全。本文将详细介绍如何在API和服务器上配置SSL证书,以提升网站的安全性和可信度。 ... [详细]
  • 本文最初发表在Thorben Janssen的Java EE博客上,每周都会分享最新的Java新闻和动态。 ... [详细]
  • Spark中使用map或flatMap将DataSet[A]转换为DataSet[B]时Schema变为Binary的问题及解决方案
    本文探讨了在使用Spark的map或flatMap算子将一个数据集转换为另一个数据集时,遇到的Schema变为Binary的问题,并提供了详细的解决方案。 ... [详细]
  • 秒建一个后台管理系统?用这5个开源免费的Java项目就够了
    秒建一个后台管理系统?用这5个开源免费的Java项目就够了 ... [详细]
  • `valueOf` 方法(即 `Object.valueOf`)用于返回指定对象的原始值。如果该对象没有对应的基元值,则直接返回对象本身。此方法在需要将对象转换为基本类型时非常有用,例如在数值运算或字符串拼接等场景中。通过深入了解 `valueOf` 的工作原理及其应用场景,开发者可以更好地处理数据类型转换问题,提高代码的健壮性和可读性。 ... [详细]
  • 在处理数据库中所有用户表的彻底清除时,目前尚未发现单一命令能够实现这一目标。因此,需要采用一种较为繁琐的方法来逐个删除相关表及其结构。具体操作可以通过编写PL/SQL脚本来实现,该脚本将动态生成并执行删除表的SQL语句。尽管这种方法相对复杂,但在缺乏更简便手段的情况下,仍是一种有效的解决方案。未来或许可以通过数据库管理工具或更高版本的数据库系统提供更简洁的处理方式。 ... [详细]
  • 为了提升单位内部沟通效率,我们开发了一套飞秋软件与OA系统的消息接口服务系统。该系统能够将OA系统中的审批、通知等信息自动同步至飞秋平台,确保员工在使用飞秋进行日常沟通的同时,也能及时获取OA系统的各类重要信息,从而实现无缝对接,提高工作效率。 ... [详细]
  • PTArchiver工作原理详解与应用分析
    PTArchiver工作原理及其应用分析本文详细解析了PTArchiver的工作机制,探讨了其在数据归档和管理中的应用。PTArchiver通过高效的压缩算法和灵活的存储策略,实现了对大规模数据的高效管理和长期保存。文章还介绍了其在企业级数据备份、历史数据迁移等场景中的实际应用案例,为用户提供了实用的操作建议和技术支持。 ... [详细]
  • 春日新芽象征着新的开始,正如学习如同春天的幼苗,虽不易察觉其成长,但每日都在进步;而中断学习则像磨刀石,虽表面无明显损耗,却日积月累地退步。这番话源自古代文人陶渊明的智慧,提醒我们珍惜时光,持续努力,方能迎来更加辉煌的未来。 ... [详细]
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社区 版权所有