Apache Common-IO 使用

Posted 醉温柔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Apache Common-IO 使用相关的知识,希望对你有一定的参考价值。

Apache Common-IO 是什么?

  Apache File 工具类,能够方便的操作 File

运行环境

  jdk 1.7

  commons-io 2.6

测试代码

技术分享
 1 package com.m.basic;
 2 
 3 import org.apache.commons.io.FileUtils;
 4 import org.junit.Test;
 5 
 6 import java.io.File;
 7 import java.io.IOException;
 8 import java.net.URL;
 9 
10 public class FileUtilTest {
11 
12     String path = "D:/malin/xxx/file.txt";
13 
14     @Test
15     public void makeFileTest() throws IOException {
16         final File file = new File("D:/malin/sss/");
17         FileUtils.forceMkdir(file);
18     }
19 
20     @Test
21     public void forceMkdirParentTest() throws IOException {
22         File file = new File(path);
23         FileUtils.forceMkdirParent(file);
24         if (!file.createNewFile()) {
25             String message = "Unable to create File " + path;
26             throw new IOException(message);
27         } else {
28             System.out.println("create success");
29         }
30     }
31 
32     @Test
33     public void writingFileTest() throws IOException {
34         File file = new File(path);
35         for (int i = 0; i < 3; i++)
36             FileUtils.writeStringToFile(file, "Hello World" + System.getProperty("line.separator"), "UTF-8", true);
37     }
38 
39     @Test
40     public void readingFIleTest() throws IOException {
41         File file = new File(path);
42         String content = FileUtils.readFileToString(file, "utf-8");
43         System.out.println(content);
44     }
45 
46     @Test
47     public void copyingFileTest() throws IOException {
48         File srcFile = new File(path);
49         File destFile = new File("D:/malin/sss/file.txt");
50         FileUtils.copyFile(srcFile, destFile);
51     }
52 
53     @Test
54     public void deletingFileTest() throws IOException {
55         FileUtils.deleteDirectory(new File(path).getParentFile());
56     }
57 
58     @Test
59     public void convertingTest() throws IOException {
60         FileUtils.copyURLToFile(new URL("http://www.baidu.com"), new File(path));
61     }
62 }
View Code

 

参考

http://commons.apache.org/proper/commons-io/description.html

以上是关于Apache Common-IO 使用的主要内容,如果未能解决你的问题,请参考以下文章

使用apache common-io 监控文件变化.md

java Apache common-io 讲解

common-io 文件监听例子

基于common-io自动监控文件及文件变化和同步文件的工具类SynFile

java实现文件监控

跟我学apache-commonscommons-io的使用