Java File类总结和FileUtils类

文件存在和类型判断

  创建出File类的对象并不代表该路径下有此文件或目录。

  用public boolean exists()可以判断文件是否存在。

  File类的对象可以是目录或者文件。

  如果是目录,public boolean isDirectory()返回true;

  如果是文件(非目录则是文件),public boolean isFile()返回true;

  但是注意需要先判断文件是否存在,如果文件不存在,上面两个方法都返回false,即不存在的File类对象既不是文件也不是目录

创建文件

  public boolean createNewFile()会创建一个新的空文件,只有该文件不存在的时候会创建,如果文件已经存在的话则返回false。

创建文件夹

  public boolean mkdir()

  创建目录,成功返回true。只能创建一个文件夹,要求所有的父目录都存在,否则创建失败。

  public boolean mkdirs()

  创建目录,成功返回true,会创建所有不存在的父目录。(注意即便最后创建失败,但是也可能创建了一些中间目录)。

  上面两个方法如果要创建的目录已经存在,不再重新创建,都返回false,只有新建目录返回true。

目录操作

  列出目录中的文件有以下方法可选:

  String[] list()

  String[] list(FilenameFilter filter)

  返回文件名数组。

  File[] listFiles()

  File[] listFiles(FileFilter filter)

  File[] listFiles(FilenameFilter filter)

  返回File数组。

  参数是文件或者文件名过滤器。

  注意返回为空和返回为null的意义是不同的。

  若不包含(符合条件的)文件,返回为空。

  但是如果返回为null,则表明调用方法的File对象可能不是一个目录,或者发生了IO错误。

删除文件

  boolean delete()方法会删除文件,如果File对象是文件则直接删除,对于目录来说,如果是空目录则直接删除,非空目录则无法删除,返回false。

  如果要删除的文件不能被删除则会抛出IOException。

  注意:不论是创建文件、创建目录还是删除文件,只有在动作真正发生的时候会返回true。

FileUtils类

  在项目中写一些工具类包装通用操作是很有必要的,看了一下apache的FileUtils类,copy了一些方法出来:

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mengdd.file; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; /*
* FileUtils copied from org.apache.commons.io.FileUtils
*/
public class FileUtils {
/**
* Construct a file from the set of name elements.
*
* @param directory
* the parent directory
* @param names
* the name elements
* @return the file
*/
public static File getFile(File directory, String... names) {
if (directory == null) {
throw new NullPointerException(
"directorydirectory must not be null");
}
if (names == null) {
throw new NullPointerException("names must not be null");
}
File file = directory;
for (String name : names) {
file = new File(file, name);
}
return file;
} /**
* Construct a file from the set of name elements.
*
* @param names
* the name elements
* @return the file
*/
public static File getFile(String... names) {
if (names == null) {
throw new NullPointerException("names must not be null");
}
File file = null;
for (String name : names) {
if (file == null) {
file = new File(name);
}
else {
file = new File(file, name);
}
}
return file;
} /**
* Opens a {@link FileInputStream} for the specified file, providing better
* error messages than simply calling <code>new FileInputStream(file)</code>
* .
* <p>
* At the end of the method either the stream will be successfully opened,
* or an exception will have been thrown.
* <p>
* An exception is thrown if the file does not exist. An exception is thrown
* if the file object exists but is a directory. An exception is thrown if
* the file exists but cannot be read.
*
* @param file
* the file to open for input, must not be {@code null}
* @return a new {@link FileInputStream} for the specified file
* @throws FileNotFoundException
* if the file does not exist
* @throws IOException
* if the file object is a directory
* @throws IOException
* if the file cannot be read
*/
public static FileInputStream openInputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file
+ "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
}
else {
throw new FileNotFoundException("File '" + file
+ "' does not exist");
}
return new FileInputStream(file);
} /**
* Opens a {@link FileOutputStream} for the specified file, checking and
* creating the parent directory if it does not exist.
* <p>
* At the end of the method either the stream will be successfully opened,
* or an exception will have been thrown.
* <p>
* The parent directory will be created if it does not exist. The file will
* be created if it does not exist. An exception is thrown if the file
* object exists but is a directory. An exception is thrown if the file
* exists but cannot be written to. An exception is thrown if the parent
* directory cannot be created.
*
* @param file
* the file to open for output, must not be {@code null}
* @param append
* if {@code true}, then bytes will be added to the
* end of the file rather than overwriting
* @return a new {@link FileOutputStream} for the specified file
* @throws IOException
* if the file object is a directory
* @throws IOException
* if the file cannot be written to
* @throws IOException
* if a parent directory needs creating but that fails
*/
public static FileOutputStream openOutputStream(File file, boolean append)
throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file
+ "' exists but is a directory");
}
if (file.canWrite() == false) {
throw new IOException("File '" + file
+ "' cannot be written to");
}
}
else {
File parent = file.getParentFile();
if (parent != null) {
if (!parent.mkdirs() && !parent.isDirectory()) {
throw new IOException("Directory '" + parent
+ "' could not be created");
}
}
}
return new FileOutputStream(file, append);
} public static FileOutputStream openOutputStream(File file)
throws IOException {
return openOutputStream(file, false);
} /**
* Cleans a directory without deleting it.
*
* @param directory
* directory to clean
* @throws IOException
* in case cleaning is unsuccessful
*/
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
} if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
} File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
} IOException exception = null;
for (File file : files) {
try {
forceDelete(file);
}
catch (IOException ioe) {
exception = ioe;
}
} if (null != exception) {
throw exception;
}
} // -----------------------------------------------------------------------
/**
* Deletes a directory recursively.
*
* @param directory
* directory to delete
* @throws IOException
* in case deletion is unsuccessful
*/
public static void deleteDirectory(File directory) throws IOException {
if (!directory.exists()) {
return;
} cleanDirectory(directory); if (!directory.delete()) {
String message = "Unable to delete directory " + directory + ".";
throw new IOException(message);
}
} /**
* Deletes a file. If file is a directory, delete it and all
* sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>You get exceptions when a file or directory cannot be deleted.
* (java.io.File methods returns a boolean)</li>
* </ul>
*
* @param file
* file or directory to delete, must not be {@code null}
* @throws NullPointerException
* if the directory is {@code null}
* @throws FileNotFoundException
* if the file was not found
* @throws IOException
* in case deletion is unsuccessful
*/
public static void forceDelete(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
boolean filePresent = file.exists();
if (!file.delete()) {
if (!filePresent) {
throw new FileNotFoundException("File does not exist: "
+ file);
}
String message = "Unable to delete file: " + file;
throw new IOException(message);
}
}
} /**
* Deletes a file, never throwing an exception. If file is a directory,
* delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
* </ul>
*
* @param file
* file or directory to delete, can be {@code null}
* @return {@code true} if the file or directory was deleted, otherwise
* {@code false}
*
*/
public static boolean deleteQuietly(File file) {
if (file == null) {
return false;
}
try {
if (file.isDirectory()) {
cleanDirectory(file);
}
}
catch (Exception ignored) {
} try {
return file.delete();
}
catch (Exception ignored) {
return false;
}
} /**
* Makes a directory, including any necessary but nonexistent parent
* directories. If a file already exists with specified name but it is
* not a directory then an IOException is thrown.
* If the directory cannot be created (or does not already exist)
* then an IOException is thrown.
*
* @param directory
* directory to create, must not be {@code null}
* @throws NullPointerException
* if the directory is {@code null}
* @throws IOException
* if the directory cannot be created or the file already exists
* but is not a directory
*/
public static void forceMkdir(File directory) throws IOException {
if (directory.exists()) {
if (!directory.isDirectory()) {
String message = "File " + directory + " exists and is "
+ "not a directory. Unable to create directory.";
throw new IOException(message);
}
}
else {
if (!directory.mkdirs()) {
// Double-check that some other thread or process hasn't made
// the directory in the background
if (!directory.isDirectory()) {
String message = "Unable to create directory " + directory;
throw new IOException(message);
}
}
}
} /**
* Returns the size of the specified file or directory. If the provided
* {@link File} is a regular file, then the file's length is returned.
* If the argument is a directory, then the size of the directory is
* calculated recursively. If a directory or subdirectory is security
* restricted, its size will not be included.
*
* @param file
* the regular file or directory to return the size
* of (must not be {@code null}).
*
* @return the length of the file, or recursive size of the directory,
* provided (in bytes).
*
* @throws NullPointerException
* if the file is {@code null}
* @throws IllegalArgumentException
* if the file does not exist.
*
*/
public static long sizeOf(File file) { if (!file.exists()) {
String message = file + " does not exist";
throw new IllegalArgumentException(message);
} if (file.isDirectory()) {
return sizeOfDirectory(file);
}
else {
return file.length();
} } /**
* Counts the size of a directory recursively (sum of the length of all
* files).
*
* @param directory
* directory to inspect, must not be {@code null}
* @return size of directory in bytes, 0 if directory is security
* restricted, a negative number when the real total
* is greater than {@link Long#MAX_VALUE}.
* @throws NullPointerException
* if the directory is {@code null}
*/
public static long sizeOfDirectory(File directory) {
checkDirectory(directory); final File[] files = directory.listFiles();
if (files == null) { // null if security restricted
return 0L;
}
long size = 0; for (final File file : files) { size += sizeOf(file);
if (size < 0) {
break; } } return size;
} /**
* Checks that the given {@code File} exists and is a directory.
*
* @param directory
* The {@code File} to check.
* @throws IllegalArgumentException
* if the given {@code File} does not exist or is not a
* directory.
*/
private static void checkDirectory(File directory) {
if (!directory.exists()) {
throw new IllegalArgumentException(directory + " does not exist");
}
if (!directory.isDirectory()) {
throw new IllegalArgumentException(directory
+ " is not a directory");
}
} }

FileUtils.java

参考资料

  File类官方文档:

  http://docs.oracle.com/javase/7/docs/api/java/io/File.html

  org.apache.commons.io.FileUtils源码:

  http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/2.4/org/apache/commons/io/FileUtils.java

  本博客旧博文:

  Java IO File类

  Java IO 用递归实现目录删除和树形目录展示 Java实现

Java File类总结和FileUtils类的更多相关文章

  1. Java File 类的使用方法详解

    Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对Java File文件操作类进行详细地分析,并将File类中的常用方法进行简单介绍,有需要的Java开发者可以看 ...

  2. Java File 类的使用方法详解(转)

    转自:http://www.codeceo.com/article/java-file-class.html Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对J ...

  3. Java——File类成员方法

    body, table{font-family: 微软雅黑} table{border-collapse: collapse; border: solid gray; border-width: 2p ...

  4. Java File类 mkdir 不能创建多层目录

    File f = new File("/home/jp/Upload"); if ((!f.exists()) || (!f.isDirectory())) {boolean re ...

  5. Java File类基础解析 1

    Java File类基础解析 1 File类的构造方法 public File(String pathname) :通过给定的路径名字符转换为抽象路径名来创建新的File实例 String path ...

  6. Java常用类:包装类,String,日期类,Math,File,枚举类

    Java常用类:包装类,String,日期类,Math,File,枚举类

  7. Java File类的简单使用

    Java File的简单使用(创建.删除.遍历.判断是否存在等) Java文件类以抽象的方式代表文件名和目录路径名.该类本身不能用来读数据或写数据,它主要用于磁盘上文件和目录的创建.文件的查找和文件的 ...

  8. Java程序员的日常—— FileUtils工具类的使用

    package cn.xingoo.learn.commons; import org.apache.commons.io.FileUtils; import org.apache.commons.i ...

  9. [19/04/04-星期四] IO技术_CommonsIO(通用IO,别人造的轮子,FileUtils类 操作文件 & IOUtilsl类 操作里边的内容 )

    一.概念 JDK中提供的文件操作相关的类,但是功能都非常基础,进行复杂操作时需要做大量编程工作.实际开发中,往往需要 你自己动手编写相关的代码,尤其在遍历目录文件时,经常用到递归,非常繁琐. Apac ...

随机推荐

  1. 用c#开发微信 (20) 微信登录网站 - 扫描二维码登录

    像京东,一号店等网站都实现了用微信来登录的功能,就是用手机上的微信扫一扫网站上的二维码,微信上确认后,即可自动用微信的帐号登录网站. 1 创建网站应用 在微信开放平台创建一个网站应用 https:// ...

  2. SQLServer学习笔记系列4

    一.写在前面的话 好多天没有记录sql学习笔记了,要坚持下去,坚信每一点的进步都是为在积蓄力量.今天看到一幅图,特此分享出来. 通过这幅图,我看到的是每人站在自己的角度看问题,感受是不一样的,就如同学 ...

  3. MVC中的默认Model绑定者DefaultModelBinder

    一.题外话 接续上一篇: MVC中Action参数绑定的过程 public IModelBinder DefaultBinder { get { if (this._defaultBinder == ...

  4. qml基础学习 基础概念

    一.概括 学习qt已有2年多的时间,从qt4.7开始使用直到现在正在使用的qt5.6,基本都在windows机器上做开发.最近有意向看了下qt的qml部分,觉着还是挺不错的,毕竟可以做嵌入式移动端产品 ...

  5. [译]学习IPython进行交互式计算和数据可视化(三)

    第二章 在本章中,我们将详细学习IPython相对以Python控制台带来的多种改进.特别的,我们将会进行下面的几个任务: 从IPython中使用系统shell以在shell和Python之间进行强大 ...

  6. Dispose() C# 优化内存

    public void Dispose() { ((IDisposable)_designer).Dispose(); } #region IDisposable Support private bo ...

  7. RDLC报表打印

    如果你的报表能正常显示,会看到RDLC工具条下的打印图标: 如果在客户端,第一次去点击此铵钮,如果当前操作者没有管理权限,会提示: Unable to load client print contro ...

  8. 在DevExpress中使用WizardControl控件构建多步向导界面

    利用好的界面控件,往往能做成比较界面体验效果.在一些界面操作里面,我们可能把它拆分为几部进行处理,这个时候引入WizardControl向导控件应该是比较不错的选择了.多步的处理方式,可以让用户避免一 ...

  9. .net概念之程序集说明

    一.程序集的一些基本概念: 程序集是包含一个或多个类型定义文件和资源文件的集合.它允许我们分离可重用类型的逻辑表示和物理表示. 程序集是一个可重用.可实施版本策略和安全策略的单元.它允许我们将类型和资 ...

  10. 介绍开源的.net通信框架NetworkComms框架 源码分析(十一)PacketBuilder

    原文网址: http://www.cnblogs.com/csdev Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 目前作者已经开源  许可是 ...