I have a folder holding a set of files, where some lines in each file contain a specific character as consisted of #, $ and %. How can I just remove these characters from those files while keeping other contents exactly the same as before. How to do that in Java?
Here's a solution with 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
}
I did not provide exception handling. Deal with that any way you want.
OR
If you are on Linux, use Java's ProcessBuilder
to build a sed
command to transform the content.
In pseudocode:
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.