2013-08-16 40 views
0

我有一個文件夾保存一組文件,其中每個文件中的某些行包含#,$和%組成的特定字符。我怎樣才能從這些文件中刪除這些字符,同時保持其他內容與以前完全相同。如何在Java中做到這一點?從一組文件中刪除一些特定字符

+3

你將不得不讀取每個文件的全部內容,並取代它。 –

回答

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 
} 

我沒有提供異常處理。以任何你想要的方式處理。

OR

如果你是在Linux上,使用Java的ProcessBuilder建設sed命令變換內容。

+1

不是逐行傳輸文件會更好嗎?這可能會導致一個OOME甚至相當小的文件... –

+0

@BoristheSpider在文件很大的情況下,當然。但是在讀取和重命名文件時(最好覆蓋原文),您必須寫入其他文件。 –

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()); 
}