0

我有一个文件夹,其中包含一组文件,其中每个文件中的某些行包含一个特定字符,由 #、$ 和 % 组成。我怎样才能从这些文件中删除这些字符,同时保持其他内容与以前完全相同。如何在 Java 中做到这一点?

4

2 回答 2

2

这是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 上,请使用 JavaProcessBuilder构建sed命令来转换内容。

于 2013-08-16T17:16:19.970 回答
0

在伪代码中:

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());
}
于 2013-08-16T17:54:12.863 回答