JAVA造轮子之-文件操作工具类

Java常用文件工具类,常规的文本内容读写、文件移动、文件复制、文件切分、文件追加写、文件更名、分页读取等;

FileUtils.java

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author JL
 * @version V1.0
 * @Description 文件操作工具类
 * @date 2019/06/14
 */
public class FileUtils {

    private static final String ENCODING = "UTF-8";

    public static boolean createFile(String filePath){
        File file = new File(filePath);
        try{
            if (file.exists()){
                return true;
            }
            File parentFile = file.getParentFile();
            if (parentFile != null && parentFile.exists()){
                return file.createNewFile();
            }
            if (new File(file.getParent()).mkdirs()){
                return file.createNewFile();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return false;
    }

    public static String readLine(String filePath, String encoding) {
        try {
            return org.apache.commons.io.FileUtils.readFileToString(new File(filePath), encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static List<String> readLines(String filePath) {
        return readLines(filePath,ENCODING);
    }

    public static List<String> readLines(String filePath, String encoding) {
        try {
            return org.apache.commons.io.FileUtils.readLines(new File(filePath), encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //分页读取文本内容
    public static List<String> readPageLines(String filePath, String encoding, int startRow, int endRow) {
        List<String> lines = readLines(filePath, encoding);
        if (lines != null && lines.size()> endRow) {
            return lines.subList(startRow, endRow);
        }
        return lines;
    }

    public static boolean copyFile(String srcPath, String targetPath) {
        try {
            org.apache.commons.io.FileUtils.copyFile(new File(srcPath), new File(targetPath));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean moveFile(String srcPath, String targetPath) {
        try {
            org.apache.commons.io.FileUtils.moveFile(new File(srcPath), new File(targetPath));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean appendFile(String filePath, String content) {
        try {
            org.apache.commons.io.FileUtils.write(new File(filePath),content, ENCODING , true);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean appendFile(String filePath, String ... contents) {
        return appendFile(filePath, Arrays.asList(contents));
    }

    public static boolean appendFile(String filePath, Collection<?> lines) {
        if (lines != null){
            try {
                org.apache.commons.io.FileUtils.writeLines(new File(filePath),lines, ENCODING, true);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean remove(String filePath){
        return org.apache.commons.io.FileUtils.deleteQuietly(new File(filePath));
    }

    public static boolean changeFileName(String filePath, String newFileName){
        return copyFile(filePath, new File(filePath).getParent() + File.separatorChar + newFileName);
    }

    //将文件拆分多个
    public static boolean splitFile(String filePath, int size){
        if (size <= 0){
            return false;
        }
        File file = new File(filePath);
        long length = file.length();
        if (length < size){
            return false;
        }
        int byteSize  = (int)(length / (long) size);//均值
        int mSize = (int)(length % (long) size);//取余
        String fileName = file.getName();
        String newFileName = fileName.substring(0,fileName.lastIndexOf("."));
        String fileSuffix = filePath.substring(filePath.lastIndexOf("."));
        System.out.println("fileName:"+fileName+",fileLength:"+length+",size:"+ size +",byteSize:"+byteSize+",mSize:"+mSize);
        RandomAccessFile raf = null;
        OutputStream os;
        try {
            for (int i=0;i<size;i++){
                if (i == (size -1)){
                    byteSize += mSize;//将剩余加到最后一个文件里
                }
                System.out.println("i="+i+",byteSize:"+byteSize);
                raf = new RandomAccessFile(file, "r");
                raf.seek(i * byteSize);
                byte [] b = new byte[byteSize];
                int s = raf.read(b);
                if (s > 0) {
                    os = new FileOutputStream(file.getParent() + File.separatorChar + newFileName + i + fileSuffix);
                    os.write(b);
                    os.flush();
                    os.close();
                }
            }
            return true;
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }finally{
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException ioe) {
                }
            }
        }
        return false;
    }

    //获取目录下所有文件(含所有子目录下的文件)
    public static List<String> fileList(String fileDir){
        File file = new File(fileDir);
        if (!file.exists()){
            return null;
        }
        List<String> fileList = new ArrayList<>();
        (new FileInterface(){
            @Override
            public void find(File fFile) {
                File [] files = null;
                if (fFile.isDirectory() && (files = fFile.listFiles()) != null){
                    for (File f : files) {
                        find(f);
                    }
                }else {
                    fileList.add(fFile.getPath());
                }
            }
        }).find(file);
        fileList.forEach(f-> System.out.println(f));
        return fileList;
    }

    interface FileInterface{
        void find(File fFile);
    }

    public static void main(String[] args) {
//        changeFileName("D:\\test\\test.txt","new.txt");
//        splitFile("D:\\test\\test.txt",3);
//        moveFile("D:\\test\\test.txt","F:\\test\\test.txt");
//        createFile("D:\\test\\ab\\11\\test.txt");
        fileList("D:\\test");
    }

}

说明:

做过项目的人都知道,很多写过的可重复利用的代码块或有用的工具类没有怎么整理,当需要的时候,又得打开项目查找一翻,虽然功能开发不难,但是又得花时间成本去写去测试,这样的重复造轮子的事情太多次了;因此不如把轮子保留,供大家一起使用;

1.这个轮子可以有:需要使用的时候确实还不存在这个组件。
2.我需要的时候轮子不在:每一种技术或工具产生都有它的项目背景,当代码写在项目里的时候,我知道有这个东西,当换了一个项目或公司后,没有备份也没有记录,这个时候你不在了,又得花时间手打一遍;
3.我不知道是不是造轮子:大多数情况下初学者很难分清楚自己是不是在重复造轮子,事实上造轮子不是我目的。我的目的是完成工作任务,任务完成的速度越快越好,质量越高越好。而不是去判断自己在不在造轮子。
4.不想重复花时间造轮子:有时候还会碰到一些并不困难但是很占时间的东西,当然有现成的轮子是花时间最少的;
5.我就是想学习轮子:初学者的并不是在重复造轮子,而是学习后以提高为自己的知识与技能。

轮子有过测试,但难免有失误,如有错误处,还敬请指出;

 

转载于:https://my.oschina.net/u/437309/blog/3067970

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值