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、结果