Java search text file


 

Java search text file

In this tutorial, you will learn how to search a text file in the current directory.

In this tutorial, you will learn how to search a text file in the current directory.

Java search text file

In this tutorial, you will learn how to search a text file in the current directory. For this, we have prompt the user to enter the name of a text file to search for. If the name does not have a .txt extension, display an error message. Then search the file in the current directory. If the file does not exist in the current directory then also display an error message.

Example:

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

class FileHandling
{
	public static void main(String[] args) 
	{
		try{
		Scanner input=new Scanner(System.in);
		System.out.print("Enter name of file: ");
		String fileName=input.nextLine();
		int mid= fileName.lastIndexOf(".");
        String fname=fileName.substring(0,mid);
        String ext=fileName.substring(mid+1,fileName.length());
		File directory=new File(".");
		if(ext.equals("txt")){
			String st=directory.getCanonicalPath();
			String file=st+"/"+fileName;
			File f=new File(file);
			if(!f.exists()){
			System.out.println("File does not exists!!!!");
            }
		 }
		else {
		
			System.out.println("File does not have .txt extension!!!!!");
		}
		}
		catch(Exception e){}
	}
}

If the file does not exist, following message will get displayed:

Enter name of file: c:/new.txt
File does not exists!!!!

If the file extension is incorrect, following message will get displayed:

Enter name of file: c:/new.doc
File does not have .txt extension!!!!!

Ads