簡體   English   中英

從一組文件中刪除一些特定字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM