Home Tutorial Java Core Java search text file

 
 

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

Related Tags for Java search text file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 10, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com