Find First occurrence of any text and stop if it exists

Hi !
I have been working on searching the documents based on any query/string.
I have been able to do it and get the counts.
But, what I need is, I don’t need any counts, I just want to check if the searched query exists in the document. If it does (no matter once, or N times). I just want it stop there and search for further docs in the directory.
Following is the code that I have used. Can you please help me optimize it as per my requirement, so that I could get a better performance, in terms of speed. Here goes the code :

public static void main(String[]args) throws Exception {

	com.aspose.words.License license = new com.aspose.words.License();
	license.setLicense("Aspose.Total.Java-License.lic");
	
	File[] files = new File("E:\\docs").listFiles();

	for (File file : files) {
	    if (file.isFile()) {
	        @SuppressWarnings("unused")
			String folderName = file.getParent();
	        String fileName =  file.getName();
	        String extensionName = fileName.substring(fileName.lastIndexOf("."));
	        if (extensionName.equals(".doc") || extensionName.equals(".docx")) {
	            //System.out.println("Processing document: " + fileName);
	            Document doc = new Document(file.getAbsolutePath());
	            FindReplaceOptions options = new FindReplaceOptions();
	            //ReplaceEvaluator callback = new ReplaceEvaluator();
	    		//options.setReplacingCallback(callback);
	    		Pattern regex = Pattern.compile("意气风发", Pattern.CASE_INSENSITIVE);
	    		int count = doc.getRange().replace(regex, "", options);
	    		//int count = callback.mMatchNumber;
	    		if(count > 0) {
	    			 System.out.println("E:\\"+file.getName());
	    			//System.out.println("E:\\"+file.getName()+" || Count="+count);
	    		}
	    		
	        }
	    }

	} 
}

Please suggest the code changes. Thanks ! :slight_smile:

@Kushal.20,

Please try using the following code that stops when it finds the first occurrence of the search string in Word document. Hope, this helps.

Document doc = new Document("E:\\temp\\in.docx");

FindReplaceOptions options = new FindReplaceOptions();
ReplaceEvaluator callback = new ReplaceEvaluator();
options.setReplacingCallback(callback);
Pattern regex = Pattern.compile("find", Pattern.CASE_INSENSITIVE);
doc.getRange().replace(regex, "", options);

boolean found = callback.flag;
if(found) {
    System.out.println("Occurred once. That's fine");
}

static class ReplaceEvaluator implements IReplacingCallback {
    boolean flag = false;
    public int replacing(ReplacingArgs e) throws Exception {
        flag = true;
        return ReplaceAction.STOP;
    }
}