介绍:FileUtils提供了好多对文件的操作,可以避免用户自己不停的去切换流的使用
一、FileUtils提供了对文件的各种操作
1、直接读取文件,将文件内容读取形成String和byte类型
2、直接将文件的内容写入文件中
3、将文件复制和文件进行移动
4、计算文件的CRC32
二、学习测试代码
package com.yezi.leran.commons.io;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.net.URLDecoder;
/**
* Created by yezi on 2014/6/1.
*/
public class LearnFileUtils {
public static void main(String []args)throws Exception{
LearnFileUtils learnFileUtils = new LearnFileUtils();
//learnFileUtils.test();
//learnFileUtils.testGetFile();
learnFileUtils.testUseTemDir();
learnFileUtils.testCheckNum();
}
public void testReadFile() throws Exception{
String path = LearnFileUtils.class.getResource("/ioutils_file/file_toarray.txt").getPath();
path = URLDecoder.decode(path, "UTF-8");
byte[] bytes = FileUtils.readFileToByteArray(new File(path));
String str = IOUtils.toString(bytes,"UTF-8");
System.out.println(str);
}
public void testGetFile() throws Exception{
String path = LearnFileUtils.class.getResource("/ioutils_file/").getPath();
path = URLDecoder.decode(path, "UTF-8");
File file = FileUtils.getFile("2.txt",path+"1.txt");
System.out.println(file.getName());
}
public void testUseTemDir() throws Exception{
String path = FileUtils.getTempDirectoryPath();
String filePath = path+"yezi_dir";
File fileDir = new File(filePath);
if(fileDir.mkdirs()){
System.out.println(fileDir.getAbsolutePath());
}
File file = new File(filePath+File.separator+"1.txt");
FileUtils.touch(file);
FileUtils.writeStringToFile(file,"小叶子",true);
System.out.println(file.getAbsolutePath());
}
public void testCheckNum() throws Exception{
String path = FileUtils.getTempDirectoryPath();
path = URLDecoder.decode(path, "UTF-8");
String filePath = path+"yezi_dir";
File file = new File(filePath+File.separator+"2.txt");
System.out.println(FileUtils.checksumCRC32(file));
}
}