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 callingnew FileInputStream(file)
* . ** At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *
* 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. ** At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *
* 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. ** The difference between File.delete() and this method are: *
- *
- A directory to be deleted does not have to be empty. *
- You get exceptions when a file or directory cannot be deleted. * (java.io.File methods returns a boolean) *
* The difference between File.delete() and this method are: *
- *
- A directory to be deleted does not have to be empty. *
- No exceptions are thrown when a file or directory cannot be deleted. *
参考资料
File类官方文档:
org.apache.commons.io.FileUtils源码:
本博客旧博文: