Home Tutorial Java Core Java search text file

 
 

Java search text file
Posted on: December 10, 2012 at 12:00 AM
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!!!!!

Related Tags for Java search text file:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.