3、File

1、创建file对象:需要指明路径

方法一:File(String path)

File file = new File("E:\kingsware\run\run_app_model1");

方法二 :File(File parent,String child)

File file1 = new File("E:\\kingsware\\run");
File file2 = new File(file1,"run_app_model1");

2、判断文件大小、目录数量的方法:file.length( )、files.length

 //获取文件大小
        long size = file3.length();
        System.out.println(size);
 //获取路径下文件数量
        File[] files = file1.listFiles();
        int number = files.length;
        System.out.println(size);

3、判断是否是文件,是否是文件夹: file3.isFile() 、file3.isDirectory()

boolean file3IsFile = file3.isFile();
System.out.println(file3IsFile);//run_testFile.txt是文件  ---》true
boolean file3directory = file3.isDirectory();
System.out.println(file3directory);//run_testFile.txt是文件  ---》false

4、判断目录或文件是否存在:file3.exists()

boolean file3IsExists = file3.exists();
boolean exists = file1.exists();
System.out.println(exists);
System.out.println(file3IsExists);

5、创建、删除文件

创建文件夹:file.mkdir()、创建文件:file.createNewFile();

删除文件:file.delete();

File file = new File("E:\\kingsware\\run\\a.text");
if(!file.exists()){
    file.createNewFile();
    //file.mkdir();
}
file.delete();

6、file过滤器

File file2 = new File("E:\\kingsware\\run");
File[] files1 = file2.listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.getName().endsWith(".txt") || pathname.isDirectory();
    }
});
for (File f : files1) {
    System.out.println(f.getName());
}

7、递归删除文件

//删除文件的方法
public static void recursiveDelete(File file) {
    //to end the recursive loop
    if (!file.exists())
        return;

    //if directory, go inside and call recursively
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            //call recursively
            recursiveDelete(f);
        }
    }
    //call delete to delete files and empty directory
    file.delete();
    //System.out.println("Deleted file/folder: "+file.getAbsolutePath());
}
public static boolean deleteFiles(File file){

    boolean result = false;

    if(file.isDirectory()){
        File[] files = file.listFiles();
        for (File childrenFile : files) {
            deleteFiles(childrenFile);
            if(!result){
                return result;
            }
        }
    }
    result = file.delete();
    return result;
}

8、递归获取文件

public static void main(String[] args){
    //表示一个文件路径
    String path = "E:\\Java\\serverDel\\";
    getFiles(path);
}
/**
 * 递归获取某路径下的所有文件,文件夹,并输出
 */
public static void getFiles(String clientBase) {
    File file = new File(clientBase);
    // 如果这个路径是文件夹
    if (file.isDirectory()) {
        // 获取路径下的所有文件
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 如果还是文件夹 递归获取里面的文件 文件夹
            if (files[i].isDirectory()) {
                System.out.println("目录:" + files[i].getPath());
                //继续读取文件夹里面的所有文件
                getFiles(files[i].getPath());
            } else {
                System.out.println("文件:" + files[i].getPath());
            }
        }
    } else {
        System.out.println("文件:" + file.getPath());
    }
}

9、获取文件或文件夹的创建或修改时间:File.lastModified(),格式化输出

   String s = "F:\\ideaxm\\app2022\\08io\\src\\main\\java\\cn\\wzt\\File3.java";
   File f = new File(s);
   Date date = new Date(f.lastModified());
   System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));

10、spring boot 下载单个文件与文件夹打包为zip下载

@GetMapping("/download")
public void download(HttpServletResponse response, @RequestParam("path") String path) throws Exception {
    // 转为path
    Path folderPath = Paths.get(path);
    // 响应为二进制数据流
    response.setContentType("application/octet-stream");
    if (!Files.isDirectory(folderPath)) { // 文件下载
        File file = new File(path);
        if (!file.exists()) {
            LOGGER.error("file not exists: " + path);
            throw new IOException("file not exists: " + path);
        }
        try (InputStream input = new FileInputStream(file);
             OutputStream output = response.getOutputStream()) {
            // 写入数据
            int len;
            // 设置10kb缓冲区
            byte[] buffer = new byte[1024 * 10];
            // 文件设置,附件的形式打开
            response.setHeader("content-disposition", "attachment; filename=" + file.getName());
            while ((len = input.read(buffer)) > 0) {
                output.write(buffer, 0, len);
            }
            output.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    } else { // 文件夹下载
        // 文件设置,附件形式打开
        response.setHeader("content-disposition", "attachment; filename=" + new String((folderPath.getFileName().toString() + ".zip").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            // 文件路径/ID
            LinkedList<String> filePath = new LinkedList<>();

            Files.walkFileTree(folderPath, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    // 开始遍历目录
                    if (!dir.equals(folderPath)) {
                        filePath.addLast(dir.getFileName().toString());
                        // 写入目录
                        ZipEntry zipEntry = new ZipEntry(filePath.stream().collect(Collectors.joining("/", "", "/")));
                        try {
                            zipOutputStream.putNextEntry(zipEntry);
                            zipOutputStream.flush();
                        } catch (IOException e) {
                            LOGGER.error(e.getMessage(), e);
                            throw new RuntimeException(e);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // 开始遍历文件
                    try (InputStream inputStream = Files.newInputStream(file)) {

                        // 创建一个压缩项,指定名称
                        String fileName = filePath.size() > 0
                                ? filePath.stream().collect(Collectors.joining("/", "", "")) + "/" + file.getFileName().toString()
                                : file.getFileName().toString();

                        ZipEntry zipEntry = new ZipEntry(fileName);
                        // 添加到压缩流
                        zipOutputStream.putNextEntry(zipEntry);
                        // 写入数据
                        int len;
                        // 设置10kb缓冲区
                        byte[] buffer = new byte[1024 * 10];
                        while ((len = inputStream.read(buffer)) > 0) {
                            zipOutputStream.write(buffer, 0, len);
                        }

                        zipOutputStream.flush();
                    } catch (IOException e) {
                        LOGGER.error(e.getMessage(), e);
                        throw new RuntimeException(e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    // 结束遍历目录
                    if (!filePath.isEmpty()) {
                        filePath.removeLast();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            zipOutputStream.closeEntry();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}

 11、文件的上传

参考:(54条消息) SpringBoot文件上传_探索er的博客-CSDN博客_springboot文件上传

posted @ 2022-07-12 15:39  jason饼干大怪兽  阅读(135)  评论(0)    收藏  举报