简体   繁体   English

当我尝试在驱动器中搜索时,程序抛出NullPointerException?

[英]Program throws NullPointerException when i try to search in drives?

I wrote a program to find file or directory. 我写了一个程序来查找文件或目录。
Its working properly when i am trying to Search file with in Directory 当我尝试在目录中搜索文件时,它正常工作
example
java FileSearch abc.txt f:\\xyz
But when i am try to search file from local drive than program throw Exception 但是当我尝试从本地驱动器搜索文件而不是程序抛出异常时
java FileSearch abc.txt f:\\
after Showing all the search result throws NullPointerException. 显示所有搜索结果后抛出NullPointerException。

nullpointerexcepion

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. 我想知道为什么抛出这个异常以及如何解决它。

list() 名单()

The documentation of listFiles() mentions that it will return null if this abstract pathname does not denote a directory, or if an I/O error occurs. listFiles()的文档提到如果此抽象路径名不表示目录,或者发生I / O错误,它将返回null Additionally, you would need to check with file.canRead() whether the application can read the directory. 此外,您需要检查file.canRead()是否应用程序可以读取目录。

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. 另一种方法是使用JDK7中引入的FileVisitor接口来执行搜索。 The link at http://docs.oracle.com/javase/tutorial/essential/io/walk.html provides details on how to use the FileVisitor interface. http://docs.oracle.com/javase/tutorial/essential/io/walk.html上的链接提供了有关如何使用FileVisitor界面的详细信息。

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. 以下代码块是搜索的重新实现,除了普通目录之外,还应该能够在Windows驱动器级别列出文件。 Note that the implementation uses Files.walkTree method that is provided as part of the NIO 2 File IO Operations. 请注意,该实现使用作为NIO 2文件IO操作的一部分提供的Files.walkTree方法。

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.");
        }
    }
}

This is how you fix it: 这是你如何解决它:

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){
    if(dir == null){
        return;
    }
    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]);
    }   
}
}

Why? 为什么? String dir[]=new File(path).list(); String dir [] = new File(path).list(); on the directory you specified is null so when you call dir.length you will get null pointer exception 在您指定的目录上为null,因此当您调用dir.length时,您将获得空指针异常

another thing that will help you understand, System.out.print(new File(path).isDirectory()); 另一件可以帮助你理解的事情是System.out.print(new File(path).isDirectory()); if its false, then you will get null pointer exception. 如果它是假的,那么你将获得空指针异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试在线程内访问静态方法时,它会抛出NullPointerException - static method throws NullPointerException when I try to access it inside thread 当我尝试在Android Studio上运行我的Android程序时出现NullPointerException - NullPointerException when I try to run my Android Program on Android Studio 当我尝试在Android中创建文件时程序抛出异常 - Program throws an exception when I try to create a file in Android 我怎样才能打印程序? 尝试访问.toString()时收到NullPointerException - How can I get my program to print? I get a NullPointerException when I try to access .toString() 当我尝试运行Struts Dispatcher时出现NullPointerException - NullPointerException when I try to run Struts Dispatcher 当我尝试在Linux上运行程序时,程序抛出错误(在Windows上运行正常) - My program throws an error when I try to run it on Linux (works fine on windows) UUID 问题,程序抛出 NullPointerException - Problem with UUID, program throws NullPointerException 尝试保存图像时为什么会出现NullPointerException? - Why am i getting NullPointerException when i try to save image? 当我尝试保留时出现java.lang.NullPointerException - java.lang.NullPointerException when i try to persist 当我尝试向数组添加值时出现java.lang.NullPointerException - java.lang.NullPointerException when I try to add value to Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM