-------------------File的使用--------------

1.File类对文件的处理

1.1目录结构:

 1.2测试对文件Test.txt处理:

    // 测试文件
@Test
public void test1() throws IOException {
String contextPath = System.getProperty("user.dir");// 获取项目名字
System.out.println("文件路径: " + contextPath + "/Test.txt");
// 创建File的第一种方式
// File file = new File(contextPath + "/Test.txt");
// 第二种方式
File file = new File(contextPath, "/Test.txt");
// 判断文件是否存在,如果不存在就新创文件
if (!file.exists()) {
// file.delete();删除文件
file.createNewFile();// 创建一个Text.txt文件
System.out.println("新增文件");
}
System.out.println("是否是文件" + file.isFile());
System.out.println("是否是目录" + file.isDirectory());
// 获取文件大小(以字节为单位)
if (file.isFile()) {
System.out.println("文件大小:" + file.length() + "字节");
}
System.out.println("此文件的上级目录是" + file.getParent());
}

结果:

文件路径:  E:\EclipseWorkspace\AllTest/Test.txt
是否是文件true
是否是目录false
文件大小:40字节
此文件的上级目录是E:\EclipseWorkspace\AllTest

 2.对目录的处理

 2.1目录结构:

 

 2.2测试代码:

    // 测试目录
@Test
public void test2() throws IOException {
String contextPath = System.getProperty("user.dir");// 获取项目名字
System.out.println("文件路径: " + contextPath + "\\text");
// 第一种方式
// File file = new File(contextPath,"text");
// 第二种
File file = new File(contextPath, "text");
System.out.println("文件是否存在" + file.exists());
if (!file.exists()) {// 如果目录不存在
file.mkdir();// 创建目录
}
// 判断文件是否存在,如果存在删除文件
System.out.println("是否是文件" + file.isFile());
System.out.println("是否是目录" + file.isDirectory());
// 列举目录下的文件的名字
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
System.out.println("目录下的文件有:");
for (File fi : listFiles) {
// 列举文件名字与大小
System.out.println(fi.getName() + " 大小 " + fi.length() * 1.0 / 1024 + "KB");
// 删除文件
System.out.println("文件将被删除");
fi.delete();
}
}
System.out.println("此文件的上级目录是" + file.getParent());
}

结果:

文件路径:  E:\EclipseWorkspace\AllTest\text
文件是否存在true
是否是文件false
是否是目录true
目录下的文件有:
1.txt 大小 0.015625KB
文件将被删除
9.20PDM截图.pdf 大小 193.109375KB
文件将被删除
web.xml 大小 0.951171875KB
文件将被删除
此文件的上级目录是E:\EclipseWorkspace\AllTest

总结:如果删除一个目录下的文件可以用上述的办法遍历一个目录下的文件然后删除文件。

-------------------FileUtils\Filenameutils\IOUtils的使用(commons-io.jar)--------------

需要注意的是tomcat的包下也有一个这个类,注意用的是commons-io的包,不要用错:

参考:http://langgufu.iteye.com/blog/2215918

分类说明演示:

1.写 文件/文件夹

2.读 文件/文件夹

3.删除 文件/文件夹

4.移动 文件/文件夹

5.copy

6.其他

7.FilenameUtils可以对文件的名字进行处理,可以快速的获取文件的扩展名与基本名字:(commons-io.jar)

补充:

 8.IOUtils实现文件拷贝

    org.apache.commons.io.IOUtils可以简单的将一个inputStream的文件读取到另一个outputStream,实现文件的拷贝,例如:

      只用传两个参数,第一个传递InputStream,第二个传递OutputStream

package cn.qlq.craw.Jsoup;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection; import org.apache.commons.io.IOUtils; public class IOutilsDownloadFile {
public static void main(String[] args) throws IOException {
String url = "http://qiaoliqiang.cn/fileDown/zfb.bmp";
URL url1 = new URL(url);
URLConnection conn = url1.openConnection();
InputStream inputStream = conn.getInputStream();
String path = "C:\\Users\\liqiang\\Desktop\\test.bmp";
OutputStream outputStream = new FileOutputStream(path);
// 利用IOutiks拷贝文件,简单快捷
IOUtils.copy(inputStream, outputStream);
}
}

其内部也是通过in.read读出内容之后,写入到output:

private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static int copy(InputStream input, OutputStream output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
public static long copyLarge(InputStream input, OutputStream output)
throws IOException {
return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);
}
public static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
throws IOException {
long count = 0;
int n = 0;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}

 IOUtils可以用来在finally中关闭流:(无条件的关闭而不抛出异常)

    public void exportExcel(OutputStream outputStream) {
// 导出之前先自动设置列宽
this.autoAllSizeColumn();
try {
workBook.write(outputStream);
} catch (IOException e) {
LOGGER.error(" exportExcel error", e);
} finally {
IOUtils.closeQuietly(outputStream);
}
}

查看源码:

    /**
* Unconditionally close an <code>OutputStream</code>.
* <p>
* Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* byte[] data = "Hello, World".getBytes();
*
* OutputStream out = null;
* try {
* out = new FileOutputStream("foo.txt");
* out.write(data);
* out.close(); //close errors are handled
* } catch (IOException e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(out);
* }
* </pre>
*
* @param output the OutputStream to close, may be null or already closed
*/
public static void closeQuietly(OutputStream output) {
closeQuietly((Closeable)output);
}
    /**
* Unconditionally close a <code>Closeable</code>.
* <p>
* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* Closeable closeable = null;
* try {
* closeable = new FileReader("foo.txt");
* // process closeable
* closeable.close();
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(closeable);
* }
* </pre>
*
* @param closeable the object to close, may be null or already closed
* @since 2.0
*/
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
}

【commons-io】File对文件与目录的处理&FileUtis,IOUtils,FilenameUtils工具的使用的更多相关文章

  1. Java基础 IO流的文件和目录的五类主要操作

    笔记: /** IO流的 文件和目录的操作 * 1.路径需要 需要两个反斜杠 或者一个单斜杠! * 绝对路径:包括盘符在内的完整的路径名! * 相对路径:在当前目录文件下的路径! * 2.File 是 ...

  2. Commons IO方便读写文件的工具类

    Commons IO是apache的一个开源的工具包,封装了IO操作的相关类,使用Commons IO可以很方便的读写文件,url源代码等. 普通地读取一个网页的源代码的代码可能如下 InputStr ...

  3. 八. 输入输出(IO)操作6.文件与目录管理

    目录是管理文件的特殊机制,同类文件保存在同一个目录下不仅可以简化文件管理,而且还可以提高工作效率.Java 语言在 java.io 包中定义了一个 File 类专门用来管理磁盘文件和目录. 每个 Fi ...

  4. commons io上传文件

    习惯了是用框架后,上传功能MVC框架基本都提供了.如struts2,springmvc! 可是假设项目中没有使用框架.而是单纯的使用jsp或servlet作为action,这时我们就能够使用commo ...

  5. Java——文件及目录File操作

    API file.listFiles(); //列出目录下所有文件及子目录fileList[i].isFile() //判断是否为文件 fileList[i].isDirectory() //判断是否 ...

  6. -1-4 java io java流 常用流 分类 File类 文件 字节流 字符流 缓冲流 内存操作流 合并序列流

      File类 •文件和目录路径名的抽象表示形式 构造方法 •public File(String pathname) •public File(String parent,Stringchild) ...

  7. File 删除给定的文件或目录

    package seday03; import java.io.File; /*** 创建一个多级目录* @author xingsir*/public class MkDirsDemo { publ ...

  8. Apache Commons IO入门教程(转)

    Apache Commons IO是Apache基金会创建并维护的Java函数库.它提供了许多类使得开发者的常见任务变得简单,同时减少重复(boiler-plate)代码,这些代码可能遍布于每个独立的 ...

  9. [转]Apache Commons IO入门教程

    Apache Commons IO是Apache基金会创建并维护的Java函数库.它提供了许多类使得开发者的常见任务变得简单,同时减少重复(boiler-plate)代码,这些代码可能遍布于每个独立的 ...

随机推荐

  1. 《GPU高性能编程CUDA实战》附录四 其他头文件

    ▶ cpu_bitmap.h #ifndef __CPU_BITMAP_H__ #define __CPU_BITMAP_H__ #include "gl_helper.h" st ...

  2. CUDA C Programming Guide 在线教程学习笔记 Part 5

    附录 A,CUDA计算设备 附录 B,C语言扩展 ▶ 函数的标识符 ● __device__,__global__ 和 __host__ ● 宏 __CUDA_ARCH__ 可用于区分代码的运行位置. ...

  3. JAVA 常用注解( JDK, Spring, AspectJ )

    JDK自带注解   @Override   表示当前方法覆盖了父类的方法   @Deprecation   表示方法已经过时,方法上有横线,使用时会有警告   @SuppviseWarnings    ...

  4. shiro 与spring的集成

    1.导入spring与shiro的jar包 2.在web.xml 文件中配置shiro的shiroFilter <filter> <filter-name>shiroFilte ...

  5. 使用django + celery + redis 异步发送邮件

    参考:http://blog.csdn.net/Ricky110/article/details/77205291 环境: centos7  +  python3.6.1 + django2.0.1  ...

  6. Java 8 日期时间API

    Java 8一个新增的重要特性就是引入了新的时间和日期API,它们被包含在java.time包中.借助新的时间和日期API可以以更简洁的方法处理时间和日期; 在介绍本篇文章内容之前,我们先来讨论Jav ...

  7. UI5-文档-2.3-使用SAPUI5工具为Eclipse开发应用程序

    用于为简单用例开发应用程序.用于Eclipse的SAPUI5应用程序开发工具提供向导来支持您以一种简单的方式创建应用程序.使用application project向导,将自动创建包含视图和控制器的必 ...

  8. ubuntu16.04 dpkg强制安装 teamviewer

    dpkg遇到安装有依赖,而依赖的包有无法安装的时候,可以试试强制安装: .90154_amd64.deb 虽然报错,但是安装后还是可以使用. 如果使用: .90154_amd64.deb 提示下面错误 ...

  9. 工作中用到和应该知道的eclipse快捷键

    Eclipse最初是由IBM公司开发的替代商业软件Visual Age for Java的下一代IDE开发环境,2001年11月贡献给开源社区,现在它由非营利软件供应商联盟Eclipse基金会(Ecl ...

  10. kafka相关资料

    先来说一下Kafka与RabbitMQ的对比: RabbitMQ,遵循AMQP协议,由内在高并发的erlanng语言开发,用在实时的对可靠性要求比较高的消息传递上. kafka是Linkedin于20 ...