【commons-io】File对文件与目录的处理&FileUtis,IOUtils,FilenameUtils工具的使用
-------------------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工具的使用的更多相关文章
- Java基础 IO流的文件和目录的五类主要操作
笔记: /** IO流的 文件和目录的操作 * 1.路径需要 需要两个反斜杠 或者一个单斜杠! * 绝对路径:包括盘符在内的完整的路径名! * 相对路径:在当前目录文件下的路径! * 2.File 是 ...
- Commons IO方便读写文件的工具类
Commons IO是apache的一个开源的工具包,封装了IO操作的相关类,使用Commons IO可以很方便的读写文件,url源代码等. 普通地读取一个网页的源代码的代码可能如下 InputStr ...
- 八. 输入输出(IO)操作6.文件与目录管理
目录是管理文件的特殊机制,同类文件保存在同一个目录下不仅可以简化文件管理,而且还可以提高工作效率.Java 语言在 java.io 包中定义了一个 File 类专门用来管理磁盘文件和目录. 每个 Fi ...
- commons io上传文件
习惯了是用框架后,上传功能MVC框架基本都提供了.如struts2,springmvc! 可是假设项目中没有使用框架.而是单纯的使用jsp或servlet作为action,这时我们就能够使用commo ...
- Java——文件及目录File操作
API file.listFiles(); //列出目录下所有文件及子目录fileList[i].isFile() //判断是否为文件 fileList[i].isDirectory() //判断是否 ...
- -1-4 java io java流 常用流 分类 File类 文件 字节流 字符流 缓冲流 内存操作流 合并序列流
File类 •文件和目录路径名的抽象表示形式 构造方法 •public File(String pathname) •public File(String parent,Stringchild) ...
- File 删除给定的文件或目录
package seday03; import java.io.File; /*** 创建一个多级目录* @author xingsir*/public class MkDirsDemo { publ ...
- Apache Commons IO入门教程(转)
Apache Commons IO是Apache基金会创建并维护的Java函数库.它提供了许多类使得开发者的常见任务变得简单,同时减少重复(boiler-plate)代码,这些代码可能遍布于每个独立的 ...
- [转]Apache Commons IO入门教程
Apache Commons IO是Apache基金会创建并维护的Java函数库.它提供了许多类使得开发者的常见任务变得简单,同时减少重复(boiler-plate)代码,这些代码可能遍布于每个独立的 ...
随机推荐
- 0_Simple__simpleSeparateCompilation
▶ 简单的将纯 C/C++ 函数放到另一个文件中,利用头文件引用到主体 .cu 中来,编译时共同编译. ▶ 源代码,把 C++ 的部分去掉了 // simpleDeviceLibrary.cuh #i ...
- 多数据源springboot-jta-atomikos
参考: https://github.com/classloader/springboot-jta-atomikos-demo 參考:二 :建议参考 https://blog.csdn.net/a ...
- JAVA 读取配置文件 xxx.properties
package config_demo; import java.io.InputStream; import java.util.Properties; public class UrlDemo { ...
- 使用django + celery + redis 异步发送邮件
参考:http://blog.csdn.net/Ricky110/article/details/77205291 环境: centos7 + python3.6.1 + django2.0.1 ...
- Spring Colud 学习
转自: http://blog.csdn.net/forezp/article/details/70148833#t0
- attr 修改IMG src
jQuery修改img的src的方法:$("#img_id").attr("src","new_src"); 定义和用法 attr() 方法 ...
- 关闭IPV6
[root@bgw-t ~]# cat > /etc/modprobe.d/ipv6.conf << EOF alias net-pf-10 off options ipv6 dis ...
- unity VideoPlayer
Events(事件) started:在调用play()后立刻调用 prepareCompleted:播放器准备完成时 seekCompleted:缓冲完成时
- struts2标签类别
要在jsp中使用Struts2的标志,先要指明标志的引入.通过jsp的代码的顶部加入以下的代码: <%@taglib prefix="s" uri="/struts ...
- C#aspx页面前台使用<%=%>无法取到后台的值
检查是不是有拼接问题,正常public和protected修饰的字段或属性均可使用<%=%>.另外,加载(Page_Load)时有没有给它们赋初始值? 答 1)前台页面只能调用本后置代码的 ...