Java 文件处理

文件和字节数组互转 工具类如下

 

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
  
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
public class FileUtil {
  
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
     
    public static void main(String[] args) {
        //把文件转为byte[]
        byte[] byte1 = file2Byte(new File("C:\\test\\test.csv"));
        //把byte[] 转存为文件
        byte2File(byte1,"C:\\test-2\\","test-2.csv");
    }
    
    //byte to file
    public static void byte2File(byte[] bfile, String fileFolder, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(fileFolder);
            if (!dir.exists()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(fileFolder + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
  
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
                }
            }
        }
    }
  
    //file to byte
    public static byte[] file2Byte(File filePath) {
        byte[] buffer = null;
  
        try {
            FileInputStream fis = new FileInputStream(filePath);
  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            logger.error("error message {}", e.getMessage());
        }
        return buffer;
    }
}
View Code

 

 

查询目录下所有文件,包括子目录

参考: Java查询目录下的所有文件(包括子目录)

调用File类中的list() 和 listFiles()方法

  • list(): 返回某个目录下的所有文件和目录的文件名,返回值是String[]
  • listFiles(): 返回某个目录下的所有文件和目录的绝对路径,返回值是File[]

递归:所有文件名字列表 需要当作参数传入。如果是在findFileList方法里,new List<String> fileNames, 再返回,会只返回当前目录的文件列表,不包括子目录。如果不用查询子目录,不用递归就可以了

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static void main(String[] args) throws Exception {
        
        //因为用了递归,fileNames 必须用参数形式 才能获取子目录内的文件名
        List<String> fileNames = new ArrayList<String>();
        
        FileUtil.findFileList(new File("C:\\test"), fileNames);
        
        for (String value : fileNames) {
            System.out.println("file:" + value);
        }        

    }

    /**
     * 读取目录下的所有文件
     * 
     * @param dir       目录
     * @param fileNames 保存文件名的集合, 因为用了递归,fileNames必须用参数形式。
     * @return 
     * @return
     */
    public static void findFileList(File dir, List<String> fileNames) {
                
        // 判断是否存在目录
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
    
        // 读取目录下的所有目录文件信息
        File[] files = dir.listFiles();
        
        // 循环,添加文件名或回调自身
        for (File file : files) {
            if (file.isFile()) { // 如果文件,添加文件全路径名
                fileNames.add(file.getPath());
            }else {
                findFileList(file, fileNames);// 如果是目录,回调自身继续查询
            }
        }
        
    }

}
View Code

 

删除文件夹和子文件夹所有文件

import java.io.File;

public class FileUtil {

    public static void main(String[] args) {
        File file = new File("C:\\test1");
        boolean result = delFiles(file);
        System.out.println("result is "+ result);
    }
    
    /**
     * 递归删除 删除某个目录及目录下的所有子目录和文件
     * 
     * @param file 文件或目录
     * @return 删除结果
     */
    public static boolean delFiles(File file) {
        boolean result = false;
        // 目录
        if (file.isDirectory()) {
            File[] childrenFiles = file.listFiles();
            for (File childFile : childrenFiles) {
                result = delFiles(childFile);
                if (!result) {
                    return result;
                }
            }
        }
        // 删除 文件、空目录
        result = file.delete();
        return result;
    }
}
View Code

 

复制文件

把某个文件 复制一份 重新保存到新的地址,参考 java 文件复制--包含Excel类型等

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
    
    public static void main(String[] args) {
        try {
            copyFiles("C:\\test\\0626.txt", "C:\\test-new", "C:\\test-new\\0626.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /** 把oldFilePath地址的文件,copy一份,保存成newFileParent文件夹下的newFilePath 文件
     * @param oldFilePath 
     * @param newFileParent
     * @param newFilePath
     * @throws IOException
     */
    public static void copyFiles(String oldFilePath, String newFileParent, String newFilePath) throws IOException {
        // old file
        File oldFile = new File(oldFilePath);
        System.out.println(oldFilePath);

        // new folder
        File newFolder = new File(newFileParent);
        if (!newFolder.exists()) {
            newFolder.mkdirs();
        }
        // new file
        File newFile = new File(newFilePath);
        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        System.out.println(newFileParent);

        // copy old file to new file
        copyFileContent(oldFile, newFile);

    }

    public static void copyFileContent(File fromFile, File toFile) throws IOException {
        FileInputStream ins = new FileInputStream(fromFile);
        FileOutputStream out = new FileOutputStream(toFile);
        byte[] b = new byte[1024];
        int n = 0;
        while ((n = ins.read(b)) != -1) {
            out.write(b, 0, n);
        }

        ins.close();
        out.close();
    }
}
View Code

 

posted on 2022-01-12 15:48  dreamstar  阅读(768)  评论(0编辑  收藏  举报