Java [코드 15] 파일 작업 관련 방법(파일 가져오기, 파일 복사, 폴더 생성, 이미지 파일 가져오기, 파일에 데이터 쓰기, 폴더 정리)

1. 설명

이것은 주로 몇 가지 작은 점을 중심으로 파일 작업과 관련된 도구 방법을 공유합니다.

  • 최신 파일은 검사되지 않습니다.
  • 고정 인코딩을 사용하여 파일 쓰기

2.도구 세부정보

이 방법은 보편적이지 않을 수 있으며, 특히 폴더 경로를 구체적으로 결정하는 매개 변수를 기반으로 폴더를 정리하는 마지막 단계에서는 더욱 그렇습니다.

2.1 경로를 기반으로 지정된 개수의 파일 목록 가져오기

rootPath이 방법은 코드 아래의 모든 파일을 검색 하고 fileCount지정된 수의 파일을 얻습니다.

  • 파일 필터링을 추가할 수 있습니다(파일 이름에 따라 특정 문자열 포함).
  • 다중 스레드 시나리오에서는 사용할 수 없습니다.
    private List<File> files = new ArrayList<>();

    /**
     * 根据路径获取指定数量的文件列表
     *
     * @param rootPath  目录
     * @param fileCount 数量
     * @return 文件列表
     */
    public List<File> getFiles(String rootPath, int fileCount) {
    
    
        List<File> fileList = new ArrayList<>();
        Path rootDir = Paths.get(rootPath);
        try {
    
    
            DirectoryStream<Path> paths = Files.newDirectoryStream(rootDir);
            for (Path path : paths) {
    
    
                File file = path.toFile();
                if (file.isDirectory()) {
    
    
                    fileList.addAll(getFiles(file.getAbsolutePath(), fileCount - fileList.size()));
                } else {
    
    
                    if (files.contains(file)) {
    
    
                        continue;
                    }
                    if (System.currentTimeMillis() - file.lastModified() < 10000) {
    
    
                        continue;
                    }
                    files.add(file);
                    fileList.add(file);
                }
                if (fileList.size() >= fileCount) {
    
    
                    break;
                }
            }
            paths.close();
            files.clear();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return fileList;
    }

2.2 파일 복사

이것은 매우 일반적인 방법입니다.

    /**
     * 复制文件
     *
     * @param sourceFile 源文件
     * @param targetFile 目标文件
     * @return 是否复制成功
     */
    public boolean fileCopyToNewFile(File sourceFile, File targetFile) {
    
    
        boolean success = false;
        try {
    
    
            FileUtils.copyFile(sourceFile, targetFile);
            success = true;
        } catch (IOException e) {
    
    
            e.printStackTrace();
            log.error("fileCopyToNewFile Failed!");
        }
        return success;
    }

2.3 매개변수를 기반으로 폴더 생성

매우 일반적으로 사용되므로 다시 설명하지 않겠습니다.

    /**
     * 根据参数创建文件夹
     *
     * @param dirPath  文件夹路径
     * @param describe 文件夹描述
     */
    public void creatDirByParam(String dirPath, String describe) {
    
    
        // 获取文件夹路径
        File file = new File(dirPath);
        // 判断文件夹是否创建,没有创建则创建新文件夹
        if (!file.exists()) {
    
    
            if (file.mkdirs()) {
    
    
                log.info(" - - - - - - 创建{} [{}] - - - - - - ", describe, dirPath);
            }
        }
    }

2.4 이미지 경로를 기반으로 이미지 가져오기

이미지 경로에 따라 브라우저에 이미지를 표시합니다.

    /**
     * 根据图片路径获取图片
     *
     * @param imagePath 图片路径
     * @return 图片数据
     */
    public ResponseEntity<byte[]> getImageByPath(String imagePath) {
    
    
        File file = new File(imagePath);
        byte[] imageBytes = {
    
    };
        try {
    
    
            imageBytes = Files.readAllBytes(file.toPath());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }

호출 방법:

    @GetMapping(value = "/getImageByImagePath", produces = "application/json;charset=UTF-8")
    public Map<String, Object> getImageByImagePath(String pic) {
    
    
        return getImageByImagePath(pic);
    }

2.5 매개변수에 따른 출력 파일

고정된 인코딩 형식을 사용하여 파일을 출력합니다.

    /**
     * 根据参数输出文件
     *
     * @param filePath 文件路径
     * @param data     数据对象
     * @param size     写出的条数
     */
    public static void writeDataToFile(String filePath, LinkedBlockingQueue<String> data, int size) {
    
    
        try {
    
    
            // 创建 BufferedWriter 对象,提高写入性能
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8));
            // 写入数据
            for (int i = 0; i < size; i++) {
    
    
                bufferedWriter.write(data.take());
                if (i < size - 1) {
    
    
                    // 写入换行符
                    bufferedWriter.newLine();
                }
            }
            // 关闭资源
            bufferedWriter.close();
            log.info("------writeDataToFile [{}] 条!------", size);
        } catch (IOException | InterruptedException e) {
    
    
            log.error("------writeDataToFile Failed [{}]------", e.getMessage());
        }
    }

2.6 매개변수에 따라 폴더 정리

현행 방식은 구체적인 판단이 있어 일반적인 방식은 아니다.

    /**
     * 根据参数清理文件夹
     *
     * @param rootPath 根目录
     * @param keepDays 保存日期
     */
    public void deleteFolderByParam(String rootPath, int keepDays) {
    
    
        try {
    
    
            String currentDay = DateUtil.format(DateUtil.offsetDay(new Date(), -keepDays), "yyyyMMdd");
            int currentDayInt = Integer.parseInt(currentDay);
            File[] devPathArr = new File(rootPath).listFiles();
            if (devPathArr != null && devPathArr.length > 0) {
    
    
                for (File devPath : devPathArr) {
    
    
                    if (devPath.isDirectory()) {
    
    
                        File[] dayPathArr = devPath.listFiles();
                        if (dayPathArr != null && dayPathArr.length > 0) {
    
    
                            for (File dayPath : dayPathArr) {
    
    
                                if (dayPath.isDirectory()) {
    
    
                                    int dirName = Integer.parseInt(dayPath.getName());
                                    if (dirName < currentDayInt) {
    
    
                                        File[] files = dayPath.listFiles();
                                        if (files != null && files.length > 0) {
    
    
                                            for (File file : files) {
    
    
                                                FileUtils.delete(file);
                                                log.info("deleteFolder[{}]file[{}]", dirName, file.getName());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
    
    
            log.error("deleteFolderByParam Failed! [{}]", e.getMessage());
        }
    }

3. 요약

파일 관련 작업은 매우 일반적으로 사용되며 지속적으로 보완될 예정입니다.

추천

출처blog.csdn.net/weixin_39168541/article/details/131601155