簡體   English   中英

播放應用程序上不可能出現NullPointerException

[英]Impossible NullPointerException on a play application

我收到了一個非常奇怪的NPE異常。 這是令人反感的代碼:

  private static int countRecurse(File file) {
        Preconditions.checkNotNull(file, "file argument");
        int entries = 0;
        for (File entry : file.listFiles()) {    //NPE on this line
            if (entry != null) {
                if (entry.isDirectory())
                    entries += countRecurse(entry);
                else
                    entries++;
            }

        }
        return entries;
    }

我在注釋行中看到NPE異常。 這是我得到的堆棧跟蹤:

java.lang.NullPointerException
        at controllers.StudyPreparation.countRecurse(StudyPreparation.java:103)
        at controllers.StudyPreparation.readDicomFiles(StudyPreparation.java:95)
        at controllers.StudyPreparation.access$100(StudyPreparation.java:30)
        at controllers.StudyPreparation$1.onReady(StudyPreparation.java:77)
        at play.core.j.JavaWebSocket$$anonfun$webSocketWrapper$1$$anonfun$apply$1.apply(JavaWebSocket.scala:48)
        at play.core.j.JavaWebSocket$$anonfun$webSocketWrapper$1$$anonfun$apply$

該代碼是Play框架應用程序的一部分,但我不認為這可能是問題的一部分...由於我已經測試了文件的無效性,因此它不能為null。 如果listFiles()方法內部發生錯誤,我希望可以在stacktrace上看到。

那么可能是什么問題呢?

編輯:

解決了檢查文件是否為目錄的問題...拋出NPE,因為file.listFiles()返回null。

即使未在javadocs上進行記錄,它也會返回null,因為該路徑不存在。 我沒有檢查,因為在我的開發機器上,該程序運行良好,該問題僅在生產服務器中出現,但是顯然與代碼中的其他部分有關...

感謝你的幫助。

來自file.listFiles()的javadoc

Returns an array of abstract pathnames denoting the files in the directory 
denoted by this abstract pathname. 

If this abstract pathname does not denote a directory, then this method returns 
null. ...

所以,檢查是否file.isDirectory()使用前file.listFiles()

由於File不是目錄,可能發生file.listFiles()返回null情況。

如果此抽象路徑名不表示目錄,則此方法返回null。 否則,將返回File對象的數組,該對象對應目錄中的每個文件或目錄。 表示目錄本身和目錄的父目錄的路徑名不包括在結果中。 使用File(File,String)構造函數從此抽象路徑名構造每個結果抽象路徑名。 因此,如果此路徑名是絕對路徑,則每個結果路徑名稱都是絕對路徑; 如果此路徑名是相對的,則每個結果路徑名將相對於同一目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM