java - 如何从JAVA中的字符串中删除ESC字符
问题描述
我想从文件中的字符串中删除 ESC 字符。我正在逐行读取文件中的数据,我想删除 ESC 字符。这是样本
public static void main(String[] args) {
String rootFolder = "D:\\sample-files";
File folder = new File(rootFolder);
List<File> files = new ArrayList<File>();
if (folder.exists()) {
files = (List<File>) FileUtils.listFiles(folder, null, true);
for (File file : files) {
Path path = Paths.get(file.getPath());
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
line = line.replaceAll("[\\u0000-\\u001f]", "");
line = line.replaceAll("\\r\\n", "\n");
line = line.replaceAll("\\r", "\n");
}
Path outputPath = Paths.get(file.getParent() + "\\" + file.getName() + "_result.txt");
Files.write(outputPath, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
解决方案
以下是我的做法:
import java.io.BufferedReader;;
import java.io.FileReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
/**
* Use {@link StringBuilder} to convert a `Character` list to {@code String}.
*/
public static String charactersToString(java.util.List<Character> chars)
{
StringBuilder sb = new StringBuilder(chars.size());
for (Character c : chars) {
sb.append(c.charValue());
}
return sb.toString();
}
/**
* Use {@link Stream} to convert {@code String} to a list of {@code chars}.
*/
public static java.util.List<Character> stringToCharacters(String text) {
return text.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
}
public static void main(String[] args)
{
java.io.File file = new java.io.File("file.txt");
java.util.List<String> content = new java.util.ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = br.readLine()) != null)
{
/* Convert String to Character array so that
* it can be easily processed each char at a time
*/
java.util.List<Character> chars = stringToCharacters(line);
/*
* Check if ascii value of char matches ESC
*/
chars.removeIf(c -> (int)c == 27);
/*
* Add the processed line to a list that will later
* be used to write back to the same file
*/
content.add(charactersToString(chars));
}
/*
* Write all processed lines back to the same file
*/
java.nio.file.Files.write(file.toPath(), content);
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
推荐阅读
- python - 按屏幕上的任意位置关闭弹出窗口
- python - 使用 spawn 的 Node.js 中的 python 没有响应
- python - 渲染图像时 imshow() 的不同程度是否会导致像素数的变化?
- laravel - 如何解决在 laravel 7 中使用 composer 安装 pusher/pusher-php-server 的问题?
- java - Android recyclerView:如何保留selectableItemBackground以保持该行突出显示?
- c# - 如何在 C# 表单的一个标签中显示文本和日期?
- javascript - 将组件发布到 Adalo 时出错
- ruby - 台风 ssl_connect_error
- java - 在 RecyclerView 实现项目点击和选项(弹出菜单)点击
- twitter - 如何将 twitter 列表的成员导出到 csv 文件?