Search and replace a word or phrase in a list of files under a directory Using Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
public class SearchNReplace {
static String extension;
static String find;
static String replace;
static int i;
public static void writefiles(File g, String find, String replace)
throws IOException {
File li[] = g.listFiles();
for (int j = 0; j < li.length; j++) {
System.out.println(li[j].getName());
if (li[j].isDirectory()) {
writefiles(li[j], find, replace);
} else if (li[j].isFile() && li[j].getName().endsWith(extension)) {
InputStream f = new FileInputStream(li[j]);
int n = f.available();
byte b[] = new byte[n];
f.read(b);
String str = new String(b, 0, n);
System.out.println(str);
String repl = str.replaceAll(find, replace);
System.out.println(repl);
byte[] wr = repl.getBytes();
f.close();
if (!repl.equals(str)) {
OutputStream o = new FileOutputStream(li[j]);
o.write(wr);
o.close();
}
}
}
}
public static void main(String args[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the directory path");
String dirname = scan.nextLine();
File f1 = new File(dirname);
if (f1.exists()) {
if (f1.length() == 0) {
System.out.println("No files exist in the directory");
} else {
System.out.println("Enter the extension");
String extension = scan.nextLine();
File[] s = f1.listFiles();
//boolean name = s[i].getName().endsWith(extension);
//if (name == false) {
for (int i = 0; i < s.length; i++) {
if(!s[i].getName().endsWith(extension)){
System.out.println(s[i].getName() + ": Invalid extension ");
} else {
//System.out.println(s[i].getName().endsWith(extension));
//for (int i = 0; i < s.length; i++) {
System.out.println(s[i].getName());
System.out.println("Enter the word to find");
String find = scan.nextLine();
InputStream f = new FileInputStream(s[i]);
int n = f.available();
byte b[] = new byte[n];
f.read(b);
String str = new String(b, 0, n);
System.out.println(str);
if(!str.contains(find))
{
System.out.println("No such word Exist");
}
else
{
System.out.println("Enter the word to replace");
String replace = scan.nextLine();
if (s[i].isDirectory() && !s[i].isHidden()) {
writefiles(s[i], find, replace);
} else if (s[i].isFile()
&& s[i].getName().endsWith(extension)) {
System.out.println(s[i].getName());
InputStream f2 = new FileInputStream(s[i]);
int n1 = f2.available();
byte b1[] = new byte[n1];
f2.read(b1);
String str1 = new String(b1, 0, n1);
System.out.println(str1);
String repl = str1.replaceAll(find, replace);
System.out.println(repl);
byte[] wr = repl.getBytes();
f2.close();
if (!repl.equals(str1)) {
OutputStream o = new FileOutputStream(s[i]);
o.write(wr);
o.close();
}
}
}
}
}
}
}
else {
System.out.println("Folder does not exist.");
}
}
}