文章目录

  • 1、需求
  • 2、代码
  • 3、结果


1、需求

Java去掉 txt 文件中的空格空行【代码记录】_Desktop

2、代码

package com.zibo.main;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemoveSpacesAndEmptyLines {

    public static void main(String[] args) {
        String inputFile = "C:\\Users\\Administrator\\Desktop\\video_film.txt";
        String outputFile = "C:\\Users\\Administrator\\Desktop\\video_film_no_spaces.txt";

        try {
            // 读取输入文件
            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            reader.close();
            // 去除空格和空行
            String cleanedContent = removeSpacesAndEmptyLines(content.toString());
            // 写入输出文件
            FileWriter writer = new FileWriter(outputFile);
            writer.write(cleanedContent);
            writer.close();
            System.out.println("去除空格和空行完成。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String removeSpacesAndEmptyLines(String text) {
        // 去除空格
        Pattern spacePattern = Pattern.compile("\\s+");
        Matcher spaceMatcher = spacePattern.matcher(text);
        text = spaceMatcher.replaceAll("");
        // 去除空行
        Pattern emptyLinePattern = Pattern.compile("^\\s*$", Pattern.MULTILINE);
        Matcher emptyLineMatcher = emptyLinePattern.matcher(text);
        text = emptyLineMatcher.replaceAll("");
        return text;
    }
}

3、结果

Java去掉 txt 文件中的空格空行【代码记录】_Desktop_02