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了一些方法出来:

  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package com.mengdd.file;
  18.  
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileNotFoundException;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24.  
  25. /*
  26. * FileUtils copied from org.apache.commons.io.FileUtils
  27. */
  28. public class FileUtils {
  29. /**
  30. * Construct a file from the set of name elements.
  31. *
  32. * @param directory
  33. * the parent directory
  34. * @param names
  35. * the name elements
  36. * @return the file
  37. */
  38. public static File getFile(File directory, String... names) {
  39. if (directory == null) {
  40. throw new NullPointerException(
  41. "directorydirectory must not be null");
  42. }
  43. if (names == null) {
  44. throw new NullPointerException("names must not be null");
  45. }
  46. File file = directory;
  47. for (String name : names) {
  48. file = new File(file, name);
  49. }
  50. return file;
  51. }
  52.  
  53. /**
  54. * Construct a file from the set of name elements.
  55. *
  56. * @param names
  57. * the name elements
  58. * @return the file
  59. */
  60. public static File getFile(String... names) {
  61. if (names == null) {
  62. throw new NullPointerException("names must not be null");
  63. }
  64. File file = null;
  65. for (String name : names) {
  66. if (file == null) {
  67. file = new File(name);
  68. }
  69. else {
  70. file = new File(file, name);
  71. }
  72. }
  73. return file;
  74. }
  75.  
  76. /**
  77. * Opens a {@link FileInputStream} for the specified file, providing better
  78. * error messages than simply calling <code>new FileInputStream(file)</code>
  79. * .
  80. * <p>
  81. * At the end of the method either the stream will be successfully opened,
  82. * or an exception will have been thrown.
  83. * <p>
  84. * An exception is thrown if the file does not exist. An exception is thrown
  85. * if the file object exists but is a directory. An exception is thrown if
  86. * the file exists but cannot be read.
  87. *
  88. * @param file
  89. * the file to open for input, must not be {@code null}
  90. * @return a new {@link FileInputStream} for the specified file
  91. * @throws FileNotFoundException
  92. * if the file does not exist
  93. * @throws IOException
  94. * if the file object is a directory
  95. * @throws IOException
  96. * if the file cannot be read
  97. */
  98. public static FileInputStream openInputStream(File file) throws IOException {
  99. if (file.exists()) {
  100. if (file.isDirectory()) {
  101. throw new IOException("File '" + file
  102. + "' exists but is a directory");
  103. }
  104. if (file.canRead() == false) {
  105. throw new IOException("File '" + file + "' cannot be read");
  106. }
  107. }
  108. else {
  109. throw new FileNotFoundException("File '" + file
  110. + "' does not exist");
  111. }
  112. return new FileInputStream(file);
  113. }
  114.  
  115. /**
  116. * Opens a {@link FileOutputStream} for the specified file, checking and
  117. * creating the parent directory if it does not exist.
  118. * <p>
  119. * At the end of the method either the stream will be successfully opened,
  120. * or an exception will have been thrown.
  121. * <p>
  122. * The parent directory will be created if it does not exist. The file will
  123. * be created if it does not exist. An exception is thrown if the file
  124. * object exists but is a directory. An exception is thrown if the file
  125. * exists but cannot be written to. An exception is thrown if the parent
  126. * directory cannot be created.
  127. *
  128. * @param file
  129. * the file to open for output, must not be {@code null}
  130. * @param append
  131. * if {@code true}, then bytes will be added to the
  132. * end of the file rather than overwriting
  133. * @return a new {@link FileOutputStream} for the specified file
  134. * @throws IOException
  135. * if the file object is a directory
  136. * @throws IOException
  137. * if the file cannot be written to
  138. * @throws IOException
  139. * if a parent directory needs creating but that fails
  140. */
  141. public static FileOutputStream openOutputStream(File file, boolean append)
  142. throws IOException {
  143. if (file.exists()) {
  144. if (file.isDirectory()) {
  145. throw new IOException("File '" + file
  146. + "' exists but is a directory");
  147. }
  148. if (file.canWrite() == false) {
  149. throw new IOException("File '" + file
  150. + "' cannot be written to");
  151. }
  152. }
  153. else {
  154. File parent = file.getParentFile();
  155. if (parent != null) {
  156. if (!parent.mkdirs() && !parent.isDirectory()) {
  157. throw new IOException("Directory '" + parent
  158. + "' could not be created");
  159. }
  160. }
  161. }
  162. return new FileOutputStream(file, append);
  163. }
  164.  
  165. public static FileOutputStream openOutputStream(File file)
  166. throws IOException {
  167. return openOutputStream(file, false);
  168. }
  169.  
  170. /**
  171. * Cleans a directory without deleting it.
  172. *
  173. * @param directory
  174. * directory to clean
  175. * @throws IOException
  176. * in case cleaning is unsuccessful
  177. */
  178. public static void cleanDirectory(File directory) throws IOException {
  179. if (!directory.exists()) {
  180. String message = directory + " does not exist";
  181. throw new IllegalArgumentException(message);
  182. }
  183.  
  184. if (!directory.isDirectory()) {
  185. String message = directory + " is not a directory";
  186. throw new IllegalArgumentException(message);
  187. }
  188.  
  189. File[] files = directory.listFiles();
  190. if (files == null) { // null if security restricted
  191. throw new IOException("Failed to list contents of " + directory);
  192. }
  193.  
  194. IOException exception = null;
  195. for (File file : files) {
  196. try {
  197. forceDelete(file);
  198. }
  199. catch (IOException ioe) {
  200. exception = ioe;
  201. }
  202. }
  203.  
  204. if (null != exception) {
  205. throw exception;
  206. }
  207. }
  208.  
  209. // -----------------------------------------------------------------------
  210. /**
  211. * Deletes a directory recursively.
  212. *
  213. * @param directory
  214. * directory to delete
  215. * @throws IOException
  216. * in case deletion is unsuccessful
  217. */
  218. public static void deleteDirectory(File directory) throws IOException {
  219. if (!directory.exists()) {
  220. return;
  221. }
  222.  
  223. cleanDirectory(directory);
  224.  
  225. if (!directory.delete()) {
  226. String message = "Unable to delete directory " + directory + ".";
  227. throw new IOException(message);
  228. }
  229. }
  230.  
  231. /**
  232. * Deletes a file. If file is a directory, delete it and all
  233. * sub-directories.
  234. * <p>
  235. * The difference between File.delete() and this method are:
  236. * <ul>
  237. * <li>A directory to be deleted does not have to be empty.</li>
  238. * <li>You get exceptions when a file or directory cannot be deleted.
  239. * (java.io.File methods returns a boolean)</li>
  240. * </ul>
  241. *
  242. * @param file
  243. * file or directory to delete, must not be {@code null}
  244. * @throws NullPointerException
  245. * if the directory is {@code null}
  246. * @throws FileNotFoundException
  247. * if the file was not found
  248. * @throws IOException
  249. * in case deletion is unsuccessful
  250. */
  251. public static void forceDelete(File file) throws IOException {
  252. if (file.isDirectory()) {
  253. deleteDirectory(file);
  254. }
  255. else {
  256. boolean filePresent = file.exists();
  257. if (!file.delete()) {
  258. if (!filePresent) {
  259. throw new FileNotFoundException("File does not exist: "
  260. + file);
  261. }
  262. String message = "Unable to delete file: " + file;
  263. throw new IOException(message);
  264. }
  265. }
  266. }
  267.  
  268. /**
  269. * Deletes a file, never throwing an exception. If file is a directory,
  270. * delete it and all sub-directories.
  271. * <p>
  272. * The difference between File.delete() and this method are:
  273. * <ul>
  274. * <li>A directory to be deleted does not have to be empty.</li>
  275. * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
  276. * </ul>
  277. *
  278. * @param file
  279. * file or directory to delete, can be {@code null}
  280. * @return {@code true} if the file or directory was deleted, otherwise
  281. * {@code false}
  282. *
  283. */
  284. public static boolean deleteQuietly(File file) {
  285. if (file == null) {
  286. return false;
  287. }
  288. try {
  289. if (file.isDirectory()) {
  290. cleanDirectory(file);
  291. }
  292. }
  293. catch (Exception ignored) {
  294. }
  295.  
  296. try {
  297. return file.delete();
  298. }
  299. catch (Exception ignored) {
  300. return false;
  301. }
  302. }
  303.  
  304. /**
  305. * Makes a directory, including any necessary but nonexistent parent
  306. * directories. If a file already exists with specified name but it is
  307. * not a directory then an IOException is thrown.
  308. * If the directory cannot be created (or does not already exist)
  309. * then an IOException is thrown.
  310. *
  311. * @param directory
  312. * directory to create, must not be {@code null}
  313. * @throws NullPointerException
  314. * if the directory is {@code null}
  315. * @throws IOException
  316. * if the directory cannot be created or the file already exists
  317. * but is not a directory
  318. */
  319. public static void forceMkdir(File directory) throws IOException {
  320. if (directory.exists()) {
  321. if (!directory.isDirectory()) {
  322. String message = "File " + directory + " exists and is "
  323. + "not a directory. Unable to create directory.";
  324. throw new IOException(message);
  325. }
  326. }
  327. else {
  328. if (!directory.mkdirs()) {
  329. // Double-check that some other thread or process hasn't made
  330. // the directory in the background
  331. if (!directory.isDirectory()) {
  332. String message = "Unable to create directory " + directory;
  333. throw new IOException(message);
  334. }
  335. }
  336. }
  337. }
  338.  
  339. /**
  340. * Returns the size of the specified file or directory. If the provided
  341. * {@link File} is a regular file, then the file's length is returned.
  342. * If the argument is a directory, then the size of the directory is
  343. * calculated recursively. If a directory or subdirectory is security
  344. * restricted, its size will not be included.
  345. *
  346. * @param file
  347. * the regular file or directory to return the size
  348. * of (must not be {@code null}).
  349. *
  350. * @return the length of the file, or recursive size of the directory,
  351. * provided (in bytes).
  352. *
  353. * @throws NullPointerException
  354. * if the file is {@code null}
  355. * @throws IllegalArgumentException
  356. * if the file does not exist.
  357. *
  358. */
  359. public static long sizeOf(File file) {
  360.  
  361. if (!file.exists()) {
  362. String message = file + " does not exist";
  363. throw new IllegalArgumentException(message);
  364. }
  365.  
  366. if (file.isDirectory()) {
  367. return sizeOfDirectory(file);
  368. }
  369. else {
  370. return file.length();
  371. }
  372.  
  373. }
  374.  
  375. /**
  376. * Counts the size of a directory recursively (sum of the length of all
  377. * files).
  378. *
  379. * @param directory
  380. * directory to inspect, must not be {@code null}
  381. * @return size of directory in bytes, 0 if directory is security
  382. * restricted, a negative number when the real total
  383. * is greater than {@link Long#MAX_VALUE}.
  384. * @throws NullPointerException
  385. * if the directory is {@code null}
  386. */
  387. public static long sizeOfDirectory(File directory) {
  388. checkDirectory(directory);
  389.  
  390. final File[] files = directory.listFiles();
  391. if (files == null) { // null if security restricted
  392. return 0L;
  393. }
  394. long size = 0;
  395.  
  396. for (final File file : files) {
  397.  
  398. size += sizeOf(file);
  399. if (size < 0) {
  400. break;
  401.  
  402. }
  403.  
  404. }
  405.  
  406. return size;
  407. }
  408.  
  409. /**
  410. * Checks that the given {@code File} exists and is a directory.
  411. *
  412. * @param directory
  413. * The {@code File} to check.
  414. * @throws IllegalArgumentException
  415. * if the given {@code File} does not exist or is not a
  416. * directory.
  417. */
  418. private static void checkDirectory(File directory) {
  419. if (!directory.exists()) {
  420. throw new IllegalArgumentException(directory + " does not exist");
  421. }
  422. if (!directory.isDirectory()) {
  423. throw new IllegalArgumentException(directory
  424. + " is not a directory");
  425. }
  426. }
  427.  
  428. }

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. 文本框只读属性,disabled不能提交

    设置文本框和文本域只读的时候用到disabled="disabled",结果后台获取不到,后来想起这个不会提交,应该用readonly

  2. Django--models一对多

    一对多--foreignkey 应用场景 当一张表中创建一行数据时,有一个单选的下拉框(可以被重复选择) 例如:创建用户信息时候,需要选择一个用户类型[普通用户][金牌用户][铂金用户]等. 创建表 ...

  3. ansible入门

    前言 最近看了一下ansible,挺火的一个配置管理工具,对比老大哥puppet,使用起来要简单一些,并且可以批量执行命令,对比同是python语言编写的saltstack,不需要安装客户端(基于pa ...

  4. CSS魔法堂:hasLayout原来是这样!

    前言 过去一直听说旧版本IE下很多诡异bug均由一个神秘角色引起的,那就是hasLayout.趁着最近突然发神经打算好好学习CSS,顺便解答多年来的疑惑. hasLayout到底是何方神圣? hasL ...

  5. 地图定位IOS8之后的定位

    从ios8开始,苹果进一步加强了对用户隐私的保护. 当app想要访问用户的隐私信息时  系统不再自动弹出一个对话框让用户授权 解决方法: (1)调用ios8.0的API 主动请求用户授权 - (voi ...

  6. django多条件筛选搜索(项目实例)

    多条件搜索在很多网站上都有用到,比如京东,淘宝,51cto,等等好多购物教育网站上都有,当然网上也有很多开源的比楼主写的好的多了去了,仅供参考,哈哈 先来一张效果图吧,不然幻想不出来是什么样的,前端样 ...

  7. Dapper学习 - Dapper的基本用法(三) - CUD

    之前介绍了Dapper的查询, 存储过程, 函数的调用, 接下来要说一下Dapper的增删改, 其实Dapper的增删改, 都是同一种模式的. 我就不分开介绍了, 直接在一个例子上展现好了. var ...

  8. 使用Unity3d做异形窗口

    项目马上上线,因为之前的登录器是使用VS2010的MFC做的,在很多电脑上会提示缺失mfcXXXX.dll,中间找寻这种解决方案,最后确定将vcredist2010_x86和我的程序打包到安装包里面, ...

  9. autofac 使用

    var builder = new ContainerBuilder();var container = builder.Build(); var assemblies = new Directory ...

  10. 删除div

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...