We are moved to new domain
Click -> www.ehowtonow.com
Sunday, 21 May 2017

How to search file from directory using Java

String[] java.io.File.list(FilenameFilter filter)

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of the list() method, except that the strings in the returned array must satisfy the filter. If the given filter is null then all names are accepted. Otherwise, a name satisfies the filter if and only if the value true results when the FilenameFilter.accept(File, String) method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes.

Parameters:
filter A filename filter

Returns:
An array of strings naming the files and directories in the directory denoted by this abstract pathname that were accepted by the given filter. The array will be empty if the directory is empty or if no names were accepted by the filter. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory

See Also:
java.nio.file.Files.newDirectoryStream(Path, String)

SearchFiles.java
package com.javatutorialcorner.regex;

import java.io.File;
import java.io.FilenameFilter;

public class SearchFiles {

 private static final String DIRECOTORY_PATH = "C:\\JTC\\Java\\Examples\\Directory\\File";

 public static void main(String args[]) {
  searchFile();
 }

 private static void searchFile() {
  File directory = new File(DIRECOTORY_PATH);

  FilenameFilter fileFilter = new FilenameFilter() {
   public boolean accept(File dir, String name) {
    return name.startsWith("w");
   }
  };

  String[] files = directory.list(fileFilter);
  if (files == null) {
   System.out.println("Directory does not exist");
  } else {
   for (int i = 0; i < files.length; i++) {
    String filename = files[i];
    System.out.println(filename);
   }
  }
 }
}

Output

word doc.docx

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to search file from directory using Java Rating: 5 Reviewed By: eHowToNow