文章目录
- 1、需求
- 2、代码
- 3、结果
1、需求
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、结果
本文链接:https://my.lmcjl.com/post/2006.html
展开阅读全文
4 评论