replace all string in directory using java code
here is the code for replacing all string in selected directory.import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Scanner; public class StringReplacer { public static void main(String[] args) { String sourcedir = "C:\\Users\\username\\Desktop\\BarikVM-SharedFolder\\loader\\databackup_sh"; String searchtext = "/home/$USER/Desktop/mytask/create_backup_dir.sh"; String replacestring = "/bahay/$USER/Desktop/mytask/create_backup_dir.sh"; String logfile = "log.txt"; try { // Clear the log file Files.deleteIfExists(Paths.get(logfile)); // Walk through files in sourcedir and its subdirectories Files.walkFileTree(Paths.get(sourcedir), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File tempFile = new File(file.toString() + ".tmp"); boolean fileModified = false; try (BufferedReader reader = new BufferedReader(new FileReader(file.toFile())); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); PrintWriter logWriter = new PrintWriter(new BufferedWriter(new FileWriter(logfile, true)))) { String line; int lineNumber = 0; while ((line = reader.readLine()) != null) { lineNumber++; if (line.contains(searchtext)) { System.out.println("Found \"" + searchtext + "\" in " + file + " on line " + lineNumber); Scanner scanner = new Scanner(System.in); System.out.print("Replace this occurrence? (y/n): "); String confirm = scanner.nextLine(); if (confirm.equalsIgnoreCase("y")) { line = line.replace(searchtext, replacestring); logWriter.println("Replaced \"" + searchtext + "\" with \"" + replacestring + "\" in " + file + " on line " + lineNumber); fileModified = true; } else { logWriter.println("Skipped replacing \"" + searchtext + "\" in " + file + " on line " + lineNumber); } } writer.write(line); writer.newLine(); } } // Ensure readers and writers are closed before deleting or moving files if (fileModified) { Files.delete(file); // Delete the original file Files.move(tempFile.toPath(), file); // Replace it with the modified file } else { Files.delete(tempFile.toPath()); // Clean up the temp file if not used } return FileVisitResult.CONTINUE; } }); System.out.println("Done!"); } catch (IOException e) { e.printStackTrace(); } } }
Last update on Aug 07, 2024
Tags: java, string, replace, file
Back to PostsComments
No comments yet.