java中关于文件操作常用工具类

简介:


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.regex.Pattern;

public class FileUtil {
 private static final Log LOG = LogFactory.getLog(FileUtil.class);

 public static boolean delete(String f) {
  try {
   File file = new File(f);
   file.delete();
   return true;
  } catch (Exception e) {
   LOG.error("delete(String) String f:" + "f", e);
   return false;
  }
 }

 public static String read(String file) {
  String ret = null;

  File f = null;
  BufferedInputStream result = null;
  ByteArrayOutputStream baos = null;

  try {
   f = new File(file);
   if (!f.exists()) {
    if (LOG.isDebugEnabled()) {
     LOG.debug(file + " does not exist.");
    }
    return ret;
   } else if (!f.isFile()) {
    // fix bug:判断是否是文件,如果是一个目录是很危险的
    LOG.warn(file + " is not a file.");
    return ret;
   }
   result = new BufferedInputStream(new FileInputStream(f));
   baos = new ByteArrayOutputStream();
   byte[] cont = new byte[1024];
   int conlen;
   while ((conlen = result.read(cont)) >= 0) {
    baos.write(cont, 0, conlen);
   }
   ret = new String(baos.toByteArray());
  } catch (Exception e) {
   LOG.error("read(String)  file:" + file, e);
  } finally {
   try {
    if (result != null)
     result.close();
    if (baos != null)
     baos.close();
    f = null;
   } catch (Exception e) {
    LOG.error("read finally ", e);
   }
  }
  return ret;
 }
 public static byte[] readBytes(String file) {
  byte[] ret = null;

  File f = null;
  BufferedInputStream result = null;
  ByteArrayOutputStream baos = null;

  try {
   f = new File(file);
   if (!f.exists()) {
    if (LOG.isDebugEnabled()) {
     LOG.debug(file + " does not exist.");
    }
    return ret;
   } else if (!f.isFile()) {
    // fix bug:判断是否是文件,如果是一个目录是很危险的
    LOG.warn(file + " is not a file.");
    return ret;
   }
   result = new BufferedInputStream(new FileInputStream(f));
   baos = new ByteArrayOutputStream();
   byte[] cont = new byte[1024];
   int conlen;
   while ((conlen = result.read(cont)) >= 0) {
    baos.write(cont, 0, conlen);
   }
   ret = (baos.toByteArray());
  } catch (Exception e) {
   LOG.error("read(String)  file:" + file, e);
  } finally {
   try {
    if (result != null)
     result.close();
    if (baos != null)
     baos.close();
    f = null;
   } catch (Exception e) {
    LOG.error("read finally ", e);
   }
  }
  return ret;
 }

 public static boolean write(String content, String file) {
  try {
   return write(content, file, false);
  } catch (Exception e) {
   LOG.error("write(String,String)  file=" + file + "   ", e);
   return false;
  }
 }

 public static boolean write(byte[] content, String file) {
  boolean ret = false;

  FileOutputStream fos = null;
  try {
   File filedir = new File(getPath(file));
   if (!filedir.exists())
    filedir.mkdirs();
   fos = new FileOutputStream(file);
   fos.write(content);
   ret = true;
  } catch (Exception e) {
   LOG.error("write(byte,String) file=" + file, e);
  } finally {
   try {
    if (fos != null)
     fos.close();
   } catch (Exception e) {
    LOG.error(e);
   }
  }
  return ret;
 }

 public static boolean write(String content, String file, boolean append) {
  boolean ret = false;
  FileOutputStream fos = null;

  try {
   long t1 = System.currentTimeMillis();
   File filedir = new File(getPath(file));
   if (!filedir.exists())
    filedir.mkdirs();
   
   if(append)
    fos = new FileOutputStream(file, append);
   else
    fos = new FileOutputStream(file);
   
   fos.write(content.getBytes());
   long t2 = System.currentTimeMillis();
   ret = true;
  } catch (Exception e) {
   LOG.error("write(String,String,boolean) file=" + file, e);
   return false;
  } finally {
   try {
    if (fos != null)
     fos.close();
   } catch (Exception e) {
    LOG.error(e);
   }
  }
  return ret;
 }

 public static String getPath(String f) {
  try {
   return f.substring(0, f.lastIndexOf("/"));
  } catch (Exception e) {
   return "./";
  }
 }

 public static String[] getFileList(String dir) {
  try {
   File parent = new File(dir);
   if (!parent.isAbsolute() || !parent.isDirectory()) {
    return null;
   }
   return parent.list();
  } catch (Exception e) {
   return null;
  }
 }

 public static String[] getFileList(final String dir, final String pattern) {
  try {

   File parent = new File(dir);
   if (!parent.isAbsolute() || !parent.isDirectory()) {
    return null;
   }
   final Pattern namePattern = Pattern.compile(pattern);
   return parent.list(new FilenameFilter() {
    public boolean accept(File dir, String name) {
     if (namePattern.matcher(name).matches()) {
      return true;
     } else {
      return false;
     }
    }
   });

  } catch (Throwable te) {
   LOG.error("getFileList[dir=" + dir + ",pattern=" + pattern
     + "]error.", te);
   return null;
  }
 }

}

目录
相关文章
|
2月前
|
存储 Java 索引
用Java语言实现一个自定义的ArrayList类
自定义MyArrayList类模拟Java ArrayList核心功能,支持泛型、动态扩容(1.5倍)、增删改查及越界检查,底层用Object数组实现,适合学习动态数组原理。
105 4
|
2月前
|
IDE JavaScript Java
在Java 11中,如何处理被弃用的类或接口?
在Java 11中,如何处理被弃用的类或接口?
171 5
|
2月前
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
164 1
|
2月前
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
183 1
|
2月前
|
Java Go 开发工具
【Java】(8)正则表达式的使用与常用类分享
正则表达式定义了字符串的模式。正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。
226 1
|
2月前
|
存储 Java 程序员
【Java】(6)全方面带你了解Java里的日期与时间内容,介绍 Calendar、GregorianCalendar、Date类
java.util 包提供了 Date 类来封装当前的日期和时间。Date 类提供两个构造函数来实例化 Date 对象。第一个构造函数使用当前日期和时间来初始化对象。Date( )第二个构造函数接收一个参数,该参数是从1970年1月1日起的毫秒数。
174 1
|
2月前
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
190 1
|
2月前
|
编解码 Java 开发者
Java String类的关键方法总结
以上总结了Java `String` 类最常见和重要功能性方法。每种操作都对应着日常编程任务,并且理解每种操作如何影响及处理 `Strings` 对于任何使用 Java 的开发者来说都至关重要。
290 5
|
3月前
|
安全 Java 数据建模
Java记录类:简化数据载体的新选择
Java记录类:简化数据载体的新选择
242 101
|
3月前
|
安全 Java 开发者
Java记录类:简化数据载体的新方式
Java记录类:简化数据载体的新方式
293 100