工具类commons-io中的FileUtils的使用

介绍: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));
    }
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值