-------------------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. leetcode268

    public class Solution { public int MissingNumber(int[] nums) { var list = nums.OrderBy(x => x).To ...

  2. Delphi Berlin 窗体代码分离风格 回到Delphi7传统风格

    回到Delphi7传统风格 Floating Form Designer You can now detach the form designer in both, VCL and FireMonke ...

  3. Python 中的垃圾回收机制(转载)

    from: https://foofish.net/python-gc.html GC作为现代编程语言的自动内存管理机制,专注于两件事:1. 找到内存中无用的垃圾资源 2. 清除这些垃圾并把内存让出来 ...

  4. check_http检查http服务

    选 项 说 明 -H, --hostname=ADDRESS 主机名或域名 -I, --IP-address=ADDRESS server的IP地址,用于在不能DNS的情况下 -p, --port=I ...

  5. Haskell语言学习笔记(24)MonadWriter, Writer, WriterT

    MonadWriter 类型类 class (Monoid w, Monad m) => MonadWriter w m | m -> w where writer :: (a,w) -& ...

  6. selenium中使用chromedriver备忘

    chromedriver是chrome浏览器的webdriver的一个实现.ChromeDriver是由Chrome开发团队来完成的因而ChromeDriver不包含在selenium包中,需要从Ch ...

  7. windows本地blast

    详细可参考https://www.jianshu.com/p/2f125cdf8262:https://blog.csdn.net/qq_34296043/article/details/544277 ...

  8. Retrofit2+Rxjava2 okhttp RxBus 使用记录

    学习 博客 http://blog.csdn.net/r17171709/article/details/51149350 @Query 后面跟要添加的字段 @Path 连接url里面{userId} ...

  9. Django入门-简单的登录

    1.登录页面   2.项目目录结构   3.需要修改四个文件 urls.py-------路径与函数之间的对应关系 views.py-------函数定义与逻辑处理 加入一个login.html文件 ...

  10. VB 共享软件防破解设计技术初探(三)

    ×××××××××××××××××××××××××××××××××××××××××××××× 其他文章快速链接: VB 共享软件防破解设计技术初探(一)http://bbs.pediy.com/sho ...