Java File Handling Search String : Search String in File using Java

Java File Handling Search String : Search String in File using Java

Java File Handling Search String is complete Java Sample code to search string inside file.

If you are not sure about Java Application  Vs Java Applet

/*
 Search hello from search1.txt
*/

import java.io.*;
import java.util.*;

public class File2 
{
	public static void main(String[] ar) throws IOException
	{
		File f1 = new File("d:\\search3.txt");		
		FileWriter w1 = new FileWriter(f1);

		if ( !(f1.exists()))
		{
			f1.createNewFile();
		}

		System.out.println("Enter Your String:");
		Scanner sc = new Scanner(System.in);
		String userstring = sc.nextLine();

		while( userstring.length()>0)
		{
			w1.write(userstring+"\n");
			w1.flush();
			userstring = sc.nextLine();
		}
		w1.close();

		System.out.println("");
		System.out.println("Enter Word to Find");
		String usersearchstring = sc.nextLine();

		String s;
		if ( f1.exists() == true)
		{
			Scanner sc1 = new Scanner(f1);
			StringBuffer sBuffer = new StringBuffer();

			while(sc1.hasNextLine())
			{	
				s = sc1.nextLine();
				sBuffer.append(s);
			}

			int index = sBuffer.indexOf(usersearchstring);	

			if(index == -1)
			{
				System.out.println("Word Not Found!");
			}
			else
			{
				System.out.println("Word Found @ Position " + index);
			}
		}
		else
		{
			System.out.println("File Does Not Exist !");
		}

	}
}

 

Leave a Reply