JavaIO 檔案的讀取,寫入,複製,壓縮,解壓等...相關操作,持續更新

loveCrane發表於2024-08-30

1. 文字檔案的讀取

文字的讀取,返回值是一個list, 如果需要返回一整個string 在while迴圈中使用StringBuilder.append 即可

/**
     * 逐行讀取文字
     *
     * @param filePath 檔案路徑
     * @return List<String>
     */
    public static List<String> readTxtFile1(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        //判斷檔案是否存在
        if (!Files.exists(path)) {
            log.error("file is not exist");
            return null;
        }
        List<String> txtList = new ArrayList<>();
        try (InputStreamReader read = new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            String lineTxt;
            while (null != (lineTxt = bufferedReader.readLine())) {
                if (StringUtils.isNotEmpty(lineTxt)) {
                    txtList.add(lineTxt);
                }
            }
        }
        return txtList;
    }

2.文字檔案的寫入

/**
 * 以指定的編碼 寫入資料
 */
private static void outputStreamWriter(String filePath, List<String> content, Charset charset, boolean append) throws IOException {
    try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filePath, append), charset);
         BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
        for (String item : content) {
            bufferedWriter.write(item);
            bufferedWriter.newLine();
        }
    }
}

3.檔案的複製

/**
 * 簡單的檔案複製,不使用緩衝區,適用於小檔案
 *
 * @param sourceFile 原始檔
 * @param targetFile 目標檔案
 */
public static void copyFile(String sourceFile, String targetFile) throws IOException {
    try (FileInputStream fileInputStream = new FileInputStream(sourceFile);
         FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) {
        byte[] b = new byte[1024];
        int length;
        while ((length = fileInputStream.read(b)) != -1) {
            fileOutputStream.write(b, 0, length);
            // 不能用 fileOutputStream.write(b) 因為最後有可能讀不夠而出錯
        }
    }
}

4.大檔案的複製

/**
 * 進行檔案的複製-高效
 * 使用位元組處理流 位元組緩衝輸入流和位元組緩衝輸出流
 *
 * @param source 源
 * @param target 複製到
 * @return boolean 結果
 */
public static boolean BufferedStreamFileCopy(String source, String target) {
    if (StringUtils.isEmpty(source) || StringUtils.isEmpty(target)) {
        log.error("檔案路徑不存在! path:{}", source);
        return false;
    }

    if (source.equals(target)) {
        log.error("複製的原始檔和目標檔案不能是同一個檔案! path:{}", source);
        return false;
    }

    Path path = Paths.get(source);
    boolean exists = Files.exists(path);
    if (!exists) {
        log.error("檔案不存在! path:{}", source);
        return false;
    }
    long currentTimeMillis = System.currentTimeMillis();
    try (BufferedInputStream bufferedInputStream = new BufferedInputStream(Files.newInputStream(path));
         BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(target)))) {
        byte[] bytes = new byte[1024];
        int length;
        while ((length = bufferedInputStream.read(bytes)) != -1) {
            bufferedOutputStream.write(bytes, 0, length);
        }
        log.info("copy file success, time:{} ms", System.currentTimeMillis() - currentTimeMillis);
        return true;
    } catch (IOException e) {
        log.error("BufferedStreamFileCopy 複製檔案異常", e);
        return false;
    }
}

5.文字檔案編碼轉換

/**
 * 編碼轉換- 如一個檔案的編碼是 gb2312 轉為 utf-8
 * 請注意,請用檔案本身的正確的編碼嘗試讀取,否則會亂碼
 *
 * @param filePath    原始檔案
 * @param oldCharset  原始字元編碼
 * @param newFilePath 新檔案
 * @param newCharset  新字元編碼
 * @throws IOException io異常
 */
private static void conversionCharset(String filePath, String oldCharset, String newFilePath, String newCharset) throws IOException {
    try (InputStreamReader reader = new InputStreamReader(Files.newInputStream(Paths.get(filePath)), oldCharset);
         BufferedReader bufferedReader = new BufferedReader(reader);
         OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(Paths.get(newFilePath)), newCharset);
         BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
        String line;
        while (null != (line = bufferedReader.readLine())) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
    }
}

相關文章