简体   繁体   English

在我的以下程序中摆脱java.lang.NullPointerException

[英]get rid of java.lang.NullPointerException in my following program

This program works fine while I search for something inside my /home/meow directory and lists all the files, but when I try to list all the files on my system's "/" it crashes after it prints the contents of the /bin directory. 当我在/ home / meow目录中搜索某些内容并列出所有文件时,该程序运行良好,但是当我尝试列出系统的“ /”上的所有文件时,在打印/ bin目录的内容后崩溃。 I also tried to execute it as SUDO java pin 我也尝试将其作为SUDO java pin执行

import java.io.*;

public class Pin
{
    public static void printFiles(String a)
    {
        File dir = new File(a);
        for(File file:dir.listFiles())
        {
            if(file.isFile())
            {
                System.out.println(file);
            }
            else
            {
                printFiles(file.toString());
            }
        }
    }
    public static void main(String[] args)
    {
        printFiles("/");
    }
}

This was my output ... 这是我的输出...

vikkyhacks java # sudo java Pin
/lib64/ld-linux-x86-64.so.2
/bin/ntfsmove
/bin/init-checkconf
/bin/chown
/bin/mt-gnu
/bin/ntfs-3g.usermap
/bin/mountpoint
/bin/plymouth
/bin/s
/bin/bunzip2
/bin/gzexe
/bin/fgconsole
/bin/ntfstruncate
/bin/i
/bin/plymouth-upstart-bridge
/bin/fgrep
/bin/ping
/bin/lesspipe
/bin/rbash
/bin/gzip
/bin/ntfsmftalloc
/bin/lowntfs-3g
/bin/tailf
/bin/bzcat
/bin/tempfile
/bin/domainname
/bin/touch
/bin/zcmp
/bin/mktemp
/bin/nano
/bin/unicode_start
/bin/ln
Exception in thread "main" java.lang.NullPointerException
    at Pin.printFiles(Pin.java:9)
    at Pin.printFiles(Pin.java:17)
    at Pin.printFiles(Pin.java:17)
    at Pin.main(Pin.java:23)

You need to check that a valid array of files are returned from File#listFiles . 您需要检查File#listFiles是否返回了有效的文件数组。 This can happen in the case of so-called logical files where the file is actually a view of physical files: 在所谓的逻辑文件的情况下可能会发生这种情况,其中文件实际上是物理文件的视图:

File[] files = dir.listFiles();
if (files != null) {
   for (File file : files) {
   ...

Alternatively you can just process anything this that is a directory 另外,您也可以处理目录中的任何内容

public static void printFiles(String a) {

   File[] files = new File(a).listFiles();
   if (files != null) {
      for (File file: files) {
         if (file.isFile()) {
            System.out.println(file);
         } else if (file.isDirectory()) {
            printFiles(file.toString());
         } 
      }
   }
}  

Your need to check whether the file or directory is exists, by using 您需要通过使用以下命令检查文件或目录是否存在

File file = new File(a);
if (file.exists()){
 for(File file:dir.listFiles())
    {
        if(file.isFile())
        {
            System.out.println(file);
        }
        else
        {
            printFiles(file.toString());
        }
    } 
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM