I wrote a program to find file or directory.
Its working properly when i am trying to Search file with in Directory
examplejava FileSearch abc.txt f:\xyz
But when i am try to search file from local drive than program throw Exceptionjava FileSearch abc.txt f:\
after Showing all the search result throws NullPointerException.
code is :
import java.io.*;
class FileSearch{
static String fd;
static boolean flg=true;
public static void main(String arr[]){
fd=arr[0];
String path=arr[1];
String dir[]=new File(path).list();
new FileSearch().finder(dir,path);
if(flg){System.out.print("File not found.");}
}
public void finder(String[] dir,String path){
for(int i=0;i<dir.length;i++){
if(dir[i].equals(fd)){
System.out.println(path+"\\"+fd);
flg=false;
}
if(new File(path,dir[i]).isDirectory())
finder(new File(path,dir[i]).list(),path+"\\"+dir[i]);
}
}
}
I want to know why this exception is thrown and how can i fix it.
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException . NullPointerException doesn't force us to use a try-catch block to handle it.
NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value. For example, using a method on a null reference.
list()
The documentation of
listFiles()
mentions that it will returnnull
if this abstract pathname does not denote a directory, or if an I/O error occurs. Additionally, you would need to check withfile.canRead()
whether the application can read the directory.
IMHO
Always use it this way;
String[] files = file.list();
if (files!=null) {
for (String f : files) processFile(f);
}
Recommend this;
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
if(fList != null){
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
}
Do let me know if you have any questions.
Another alternative is to using the FileVisitor interface introduced in JDK7 to perform the search. The link at http://docs.oracle.com/javase/tutorial/essential/io/walk.html provides details on how to use the FileVisitor interface.
The following code block is a re implementation of the search that should be able to list files at a windows drive level in addition to normal directories. Note that the implementation uses Files.walkTree method that is provided as part of the NIO 2 File IO Operations.
public class FileSearch {
static String fd;
static boolean flg = true;
static class FileSearchVisitor extends SimpleFileVisitor<Path> {
private final Path pathToSearch;
boolean found;
FileSearchVisitor(Path pathToSearch) {
found = false;
this.pathToSearch = pathToSearch;
}
public boolean isFound() {
return found;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
super.preVisitDirectory(dir, attrs);
if (pathToSearch.getFileName().equals(dir.getFileName())) {
System.out.println("Found " + pathToSearch);
found = true;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
super.visitFile(file, attrs);
if (pathToSearch.getFileName().equals(file.getFileName())) {
System.out.println("Found " + pathToSearch);
found = true;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println("Visit failed for file at path : " + file);
exc.printStackTrace();
return FileVisitResult.CONTINUE;
}
}
public static void main(String arr[]) throws Exception {
fd = arr[0];
String path = arr[1];
final Path searchFile = Paths.get(fd);
Path filePath = Paths.get(path);
FileSearchVisitor visitor = new FileSearchVisitor(searchFile);
Files.walkFileTree(filePath, visitor);
if (!visitor.isFound()) {
System.out.print("File not found.");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With