Java文件操作工具类fileUtil实例【文件增删改,复制等】

所属分类: 软件编程 / java 阅读数: 17
收藏 0 赞 0 分享

本文实例讲述了Java文件操作工具类fileUtil。分享给大家供大家参考,具体如下:

package com.gcloud.common;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * 文件工具类
 * Created by charlin on 2017/9/8.
 */
public class FileUtil {
  /**
   * 读取文件内容
   *
   * @param is
   * @return
   */
  public static String readFile(InputStream is) {
    BufferedReader br = null;
    StringBuffer sb = new StringBuffer();
    try {
      br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
      String readLine = null;
      while ((readLine = br.readLine()) != null) {
        sb.append(readLine);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        br.close();
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }
  /**
   * 判断指定的文件是否存在。
   *
   * @param fileName
   * @return
   */
  public static boolean isFileExist(String fileName) {
    return new File(fileName).isFile();
  }
  /**
   * 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
   * 注意:可能会在返回false的时候创建部分父目录。
   *
   * @param file
   * @return
   */
  public static boolean makeDirectory(File file) {
    File parent = file.getParentFile();
    if (parent != null) {
      return parent.mkdirs();
    }
    return false;
  }
  /**
   * 返回文件的URL地址。
   *
   * @param file
   * @return
   * @throws MalformedURLException
   */
  public static URL getURL(File file) throws MalformedURLException {
    String fileURL = "file:/" + file.getAbsolutePath();
    URL url = new URL(fileURL);
    return url;
  }
  /**
   * 从文件路径得到文件名。
   *
   * @param filePath
   * @return
   */
  public static String getFileName(String filePath) {
    File file = new File(filePath);
    return file.getName();
  }
  /**
   * 从文件名得到文件绝对路径。
   *
   * @param fileName
   * @return
   */
  public static String getFilePath(String fileName) {
    File file = new File(fileName);
    return file.getAbsolutePath();
  }
  /**
   * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
   *
   * @param filePath
   * @return
   */
  public static String toUNIXpath(String filePath) {
    return filePath.replace("", "/");
  }
  /**
   * 从文件名得到UNIX风格的文件绝对路径。
   *
   * @param fileName
   * @return
   */
  public static String getUNIXfilePath(String fileName) {
    File file = new File(fileName);
    return toUNIXpath(file.getAbsolutePath());
  }
  /**
   * 得到文件后缀名
   *
   * @param fileName
   * @return
   */
  public static String getFileExt(String fileName) {
    int point = fileName.lastIndexOf('.');
    int length = fileName.length();
    if (point == -1 || point == length - 1) {
      return "";
    } else {
      return fileName.substring(point + 1, length);
    }
  }
  /**
   * 得到文件的名字部分。 实际上就是路径中的最后一个路径分隔符后的部分。
   *
   * @param fileName
   * @return
   */
  public static String getNamePart(String fileName) {
    int point = getPathLastIndex(fileName);
    int length = fileName.length();
    if (point == -1) {
      return fileName;
    } else if (point == length - 1) {
      int secondPoint = getPathLastIndex(fileName, point - 1);
      if (secondPoint == -1) {
        if (length == 1) {
          return fileName;
        } else {
          return fileName.substring(0, point);
        }
      } else {
        return fileName.substring(secondPoint + 1, point);
      }
    } else {
      return fileName.substring(point + 1);
    }
  }
  /**
   * 得到文件名中的父路径部分。 对两种路径分隔符都有效。 不存在时返回""。
   * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。
   *
   * @param fileName
   * @return
   */
  public static String getPathPart(String fileName) {
    int point = getPathLastIndex(fileName);
    int length = fileName.length();
    if (point == -1) {
      return "";
    } else if (point == length - 1) {
      int secondPoint = getPathLastIndex(fileName, point - 1);
      if (secondPoint == -1) {
        return "";
      } else {
        return fileName.substring(0, secondPoint);
      }
    } else {
      return fileName.substring(0, point);
    }
  }
  /**
   * 得到路径分隔符在文件路径中最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
   *
   * @param fileName
   * @return
   */
  public static int getPathLastIndex(String fileName) {
    int point = fileName.lastIndexOf("/");
    if (point == -1) {
      point = fileName.lastIndexOf("");
    }
    return point;
  }
  /**
   * 得到路径分隔符在文件路径中指定位置前最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
   *
   * @param fileName
   * @param fromIndex
   * @return
   */
  public static int getPathLastIndex(String fileName, int fromIndex) {
    int point = fileName.lastIndexOf("/", fromIndex);
    if (point == -1) {
      point = fileName.lastIndexOf("", fromIndex);
    }
    return point;
  }
  /**
   * 得到路径分隔符在文件路径中首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
   *
   * @param fileName
   * @return
   */
  public static int getPathIndex(String fileName) {
    int point = fileName.indexOf("/");
    if (point == -1) {
      point = fileName.indexOf("");
    }
    return point;
  }
  /**
   * 得到路径分隔符在文件路径中指定位置后首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
   *
   * @param fileName
   * @param fromIndex
   * @return
   */
  public static int getPathIndex(String fileName, int fromIndex) {
    int point = fileName.indexOf("/", fromIndex);
    if (point == -1) {
      point = fileName.indexOf("", fromIndex);
    }
    return point;
  }
  /**
   * 将文件名中的类型部分去掉。
   *
   * @param filename
   * @return
   */
  public static String removeFileExt(String filename) {
    int index = filename.lastIndexOf(".");
    if (index != -1) {
      return filename.substring(0, index);
    } else {
      return filename;
    }
  }
  /**
   * 得到相对路径。 文件名不是目录名的子节点时返回文件名。
   *
   * @param pathName
   * @param fileName
   * @return
   */
  public static String getSubpath(String pathName, String fileName) {
    int index = fileName.indexOf(pathName);
    if (index != -1) {
      return fileName.substring(index + pathName.length() + 1);
    } else {
      return fileName;
    }
  }
  /**
   * 删除一个文件。
   *
   * @param filename
   * @throws IOException
   */
  public static void deleteFile(String filename) throws IOException {
    File file = new File(filename);
    if (file.isDirectory()) {
      throw new IOException("IOException -> BadInputException: not a file.");
    }
    if (!file.exists()) {
      throw new IOException("IOException -> BadInputException: file is not exist.");
    }
    if (!file.delete()) {
      throw new IOException("Cannot delete file. filename = " + filename);
    }
  }
  /**
   * 删除文件夹及其下面的子文件夹
   *
   * @param dir
   * @throws IOException
   */
  public static void deleteDir(File dir) throws IOException {
    if (dir.isFile())
      throw new IOException("IOException -> BadInputException: not a directory.");
    File[] files = dir.listFiles();
    if (files != null) {
      for (int i = 0; i < files.length; i++) {
        File file = files[i];
        if (file.isFile()) {
          file.delete();
        } else {
          deleteDir(file);
        }
      }
    }
    dir.delete();
  }
  /**
   * 复制文件
   *
   * @param src
   * @param dst
   * @throws Exception
   */
  public static void copy(File src, File dst) throws Exception {
    int BUFFER_SIZE = 4096;
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
      out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
      byte[] buffer = new byte[BUFFER_SIZE];
      int len = 0;
      while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
      }
    } catch (Exception e) {
      throw e;
    } finally {
      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        out = null;
      }
    }
  }
  /**
   * @复制文件,支持把源文件内容追加到目标文件末尾
   * @param src
   * @param dst
   * @param append
   * @throws Exception
   */
  public static void copy(File src, File dst, boolean append) throws Exception {
    int BUFFER_SIZE = 4096;
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
      out = new BufferedOutputStream(new FileOutputStream(dst, append), BUFFER_SIZE);
      byte[] buffer = new byte[BUFFER_SIZE];
      int len = 0;
      while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
      }
    } catch (Exception e) {
      throw e;
    } finally {
      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        out = null;
      }
    }
  }
}

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

更多精彩内容其他人还在看

Java数据类型的规则

这篇文章主要介绍了Java数据类型的规则的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Spring整合TimerTask实现定时任务调度

这篇文章主要介绍了Spring整合TimerTask实现定时任务调度的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

详解SpringMVC使用MultipartFile实现文件的上传

本篇文章主要介绍了SpringMVC使用MultipartFile实现文件的上传,本地的文件上传到资源服务器上,比较好的办法就是通过ftp上传。这里是结合SpringMVC+ftp的形式上传的,有兴趣的可以了解一下。
收藏 0 赞 0 分享

SpringMVC上传文件的三种实现方式

本篇文章主要介绍了SpringMVC上传文件的三种实现方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例

本篇文章主要介绍了微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

浅析Java中的继承与组合

本文将介绍组合和继承的概念及区别,并从多方面分析在写代码时如何进行选择。文中通过示例代码介绍的很详细,有需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

利用反射获取Java类中的静态变量名及变量值的简单实例

下面小编就为大家带来一篇利用反射获取Java类中的静态变量名及变量值的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java启动线程的3种方式对比分析

这篇文章主要为大家对比分析了java启动线程的3种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SpringMVC上传和解析Excel方法

这篇文章主要介绍了SpringMVC上传和解析Excel方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

JAVA中String类与StringBuffer类的区别

这篇文章主要为大家详细介绍了JAVA中String类与StringBuffer类的区别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多