[英]remove some specific characters from a set of files
我有一个文件夹,其中包含一组文件,其中每个文件中的某些行包含由#,$和%组成的特定字符。 如何从这些文件中删除这些字符,同时保持其他内容与以前完全相同。 如何用Java做到这一点?
这是Java NIO的解决方案。
Set<Path> paths = ... // get your file paths
// for each file
for (Path path : paths) {
String content = new String(Files.readAllBytes(path)); // read their content
content = content.replace("$", "").replace("%", "").replace("#", ""); // replace the content in memory
Files.write(path, content.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); // write the new content
}
我没有提供异常处理。 以任何你想要的方式处理。
要么
如果您使用的是Linux,请使用Java的ProcessBuilder
构建一个sed
命令来转换内容。
在伪代码中:
files = new File("MyDirectory").list();
for (file : files) {
tempfile = new File(file.getName() + ".tmp", "w");
do {
buffer = file.read(some_block_size);
buffer.replace(targetCharacters, replacementCharacter);
tempfile.write(buffer);
} while (buffer.size > 0);
file.delete();
tempfile.rename(file.getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.