How to check the presence of a string in between specified strings in a file in java

Suppose, there is a requirement to check that a particular string is present in a file but with a restriction that it should only be present between a pair of string. For example the string “your age” should be present in between “What is” and “?”.

Working code follows:

/*
* Just pass a String array with necessary parameters and you are good to go
*/
public boolean verifyTextPresence(String[] params)
			throws FileNotFoundException {
		String filePath = params[0];
                //string before the string to check
		String startStr = params[1];
                //string after the string to check
		String endStr = params[2];
                //string to find
                String strToCheck = params[3];
		boolean isStrPresent = false;
		Scanner scan = null;
		try {
			scan = new Scanner(new File(filePath));
			boolean isStartTag = false;
			while (scan.hasNextLine()) {
				String line = scan.nextLine();
				int startIndex = 0, endIndex=0;
				if (line.contains(startStr)) {
                                        // string flag to indicate that start string has been found  
					isStartTag = true;
					startIndex = line.indexOf(startStr);
				}
                                // we need to check that the end string is present and 
                                // it occurs after the start string, not before it
				if(isStartTag && line.contains(endStr)){
                                        // get the location of end string
					endIndex = line.indexOf(endStr, startIndex);
                                           // check if the string to find exists between the start and end strings
		                           if(line.substring(startIndex, endIndex).contains(strToCheck)){
						isStrPresent = true;
                                                //terminate loop if the string has been found in a line
                                                break; 	
					    }
				}			
                       }
			if (isStrPresent) {
				System.out.println("String \"" + strToCheck
						+ "\" is present between the start and end strings \""
						+ startStr + "\" and \"" + endStr + "\" respectively");
				return true;
			}
                        //print error message if the string cannot be found
			String errMesg = "String \"" + strToCheck
					+ "\" is NOT present between the start and end strings \""
					+ startStr + "\" and \"" + endStr + "\" respectively";
			System.out.println(errMesg);
		} catch (FileNotFoundException fne) {
			throw fne;
		} finally {
			if(scan!=null){
				scan.close();
			}
		}
		return false;
	}

Let’s tweak in:

1. Always catch FileNotFoundException when dealing with files.
2. Close the scanner object in finally block. Starting java 7 this may be avoided if try-with-resources statement is used in which the resources are automatically closed.

Leave a Reply