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