首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 讀取文字檔並移除空白行寫入新檔案

     編輯:Java 相關知識

需求場景

處理大型日誌或資料檔時,常需過濾掉空白行以節省空間或利於後續解析。

完整實作

import java.io.*;

public class RemoveBlankLines {
    public static void main(String[] args) {
        String inputPath = "file1";
        String outputPath = "file2";

        try (BufferedReader br = new BufferedReader(
                     new InputStreamReader(new BufferedInputStream(new FileInputStream(inputPath)), "UTF-8");
                 FileWriter fw = new FileWriter(outputPath)) {

            String line;
            int count = 0;
            while ((line = br.readLine()) != null) {
                if (!line.isEmpty()) {
                    fw.write(line + "\n");
                    System.out.println(++count);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

關鍵細節

  • 使用 try-with-resources 自動關閉流,避免資源洩漏。
  • 指定 UTF-8 編碼讀取,防止中文亂碼。
  • line.isEmpty() 判斷空白行,若需保留含空白字元的行可改用 line.trim().isEmpty()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved