我在创建分类器时遇到问题。我的现有路径导致 NullPointerException
。我在 Eclipse 中使用 OpenCV 2.4.11。操作系统是 Windows,这就是我在文件夹之间添加另一个反斜杠的原因。当我在文件资源管理器中插入带有单反斜杠的路径时,它会正确打开 XML 文件。我的代码如下所示:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.out.println("\nRunning FaceDetector");
String path = "C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
System.out.println("path:" + path);
CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource(path).getPath());
输出是:
Running FaceDetector
path:C:\Users\Juergen\OpenCV\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml
Exception in thread "main" java.lang.NullPointerException
at FaceDetector.main(FaceDetector.java:24)
代码基于以下instruction .
对于抛出 NullPointerException 的原因的任何想法都表示赞赏。
谢谢
最佳答案
当我们查看 Java API 时,我们会发现:
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
因此你必须在你的绝对路径前加一个'/':
String path = "/C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
而且您还应该摆脱 windows 文件分隔符。 Java 理解 unix 文件分隔符并知道如何在 windows 系统上处理它:
String path = "/C:/Users/Juergen/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";
I replaced my string by Yours, nothing changed. Still get a NullPointerException. The check
if (!new File(path).exists()) { throw new FileNotFoundException("Yikes!");}
does not throw any Exception – Jürgen K
然后从 *.class.getResource(path)
你得到一个 URL
和从 URL
的 getPath( )
方法你会得到一个 String
,它很可能与你的原始字符串相同。
您是否尝试过直接使用它(使用前导“/”)?
关于java - 现有路径上的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053140/