0

The below code can search the values, but now I have to replace the value which is being searched .Please help I'm new to java .This should work as any text editor which has a search and replace facility .

public class TestClass {

    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Path to be searched");

        String directory = scanner.next();
        System.out.println("Enter String to be searched");
        String searchString = scanner.next();
        searchDirectory(directory, searchString);

    }
    static void searchDirectory(String directory, String searchString){
        File dir = new File(directory);
        if(!dir.isDirectory()){
            System.err.println("PATH ENTERED is not directory");
            return;
        }
        try{
           for (File file : dir.listFiles()) {
              if(!file.isDirectory()){

                  String  fileName = file.getName().toLowerCase();

                  if (fileName.endsWith((".txt"))
                          ||fileName.endsWith((".log"))) {

                        @SuppressWarnings("resource")
                        BufferedReader br = new BufferedReader(new FileReader(file));
                            String line;
                            int Count =0,
                                index = -1;

                            while ((line = br.readLine()) != null) {
                                Count++;
                               index = line.indexOf(searchString);

                                if(index != -1){
                                    System.out.println("Text '"+searchString+"' Found at position "+index +" in file "+ fileName +" at Line No "+Count);
                                }
                            }
                        }

          }else{
              System.err.println("TestClass.searchDirectory(DIR)"+file.getAbsolutePath());
            //  searchDirectory(file.getAbsolutePath(), searchString);
          }

           }
           }catch(Exception e){
               e.printStackTrace();
           }

    }
}
  • 1
    What do you mean by *replace the value*? Can't you just call `searchDirectory(directory, someOtherString);`? – Idos Mar 22 '16 at 08:39
  • I guess you mean a search-and-replace operation? If so you'd have to either keep the content of a file in memory until you're done reading, then replace the search string (might do that while storing) and finally overwrite the file's content. If the file's are larger you could use a temporary file to write to and then replace the original file with the temporary one (or read the temporary and write the content to the original file as to keep permissions, creation timestamp etc.). – Thomas Mar 22 '16 at 08:44
  • I mean if want to search for a word called 'security' the directory iam able to search for it bt now i want to replace the search value with other name – Ambarish Karan Mar 22 '16 at 08:44
  • Have a look here for some more information: http://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-file – Thomas Mar 22 '16 at 08:45
  • you want: **1-** search again with new word? **2-** replace the word in file that matches the search word to a new word? please pick one :) – Yazan Mar 22 '16 at 09:00
  • replace the word in file that matches the search word to a new word – Ambarish Karan Mar 22 '16 at 09:02

1 Answers1

1

You can try this:

public class TestClass {

public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter Path to be searched");

    String directory = scanner.next();
    System.out.println("Enter String to be searched");
    String searchString = scanner.next();
    searchDirectory(directory, searchString);

}
static void searchDirectory(String directory, String searchString) {
    File dir = new File(directory);
    if (!dir.isDirectory()) {
        System.err.println("PATH ENTERED is not directory");
        return;
    }
    try {
        for (File file : dir.listFiles()) {
            if (!file.isDirectory()) {

                String  fileName = file.getName().toLowerCase();

                if (fileName.endsWith((".txt"))
                    || fileName.endsWith((".log"))) {

                    @SuppressWarnings("resource")
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String line;
                    int Count = 0,
                        index = -1;

                    String replacedText = "";
                    boolean hasValue = false;
                    while ((line = br.readLine()) != null) {
                        Count++;
                        index = line.indexOf(searchString);

                        if (index != -1) {
                            System.out.println("Text '" + searchString + "' Found at position " + index + " in file " + fileName + " at Line No " + Count);
                            line.replace(searchString, newString);
                            hasValue = true;
                        }

                        replacedText += line;

                        br.close();

                        if (hasValue) {
                            FileWriter writer = new FileWriter(file);
                            writer.write(replacedText);
                            writer.close();
                        }
                    }
                }
            }
            else {
                System.err.println("TestClass.searchDirectory(DIR)" + file.getAbsolutePath());
                //  searchDirectory(file.getAbsolutePath(), searchString);
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
Gregory Prescott
  • 574
  • 3
  • 10