我在以下简单代码中遇到空指针异常:
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
}
}
抛出的是 JFileChooser 构造函数。我收到以下异常消息:
Exception in thread "main" java.lang.NullPointerException
at sun.awt.shell.Win32ShellFolder2.getFileSystemPath(Unknown Source)
at sun.awt.shell.Win32ShellFolder2.access$400(Unknown Source)
at sun.awt.shell.Win32ShellFolder2$10.call(Unknown Source)
at sun.awt.shell.Win32ShellFolder2$10.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
我在谷歌搜索问题时发现的唯一一件事是关于 Java6 回归的报告,所以我做的第一件事就是更新到 JDK 7u45 并扔掉所有旧版本的垃圾。现在仅安装了 JRE 7u45 和 JDK 7u45。
调用 System.getProperty("java.runtime.version")
返回 1.7.0_45-b18
所以我应该是最新的。
不过,我仍然遇到同样的错误。我在 Eclipse 上运行代码,除了标准 JRE 之外从未链接过任何库。
有什么线索吗?
编辑:这是尝试进入 JFileChooser 构造函数时的调用堆栈:
Thread [main] (Suspended)
FileNotFoundException(Throwable).<init>(String) line: 264
FileNotFoundException(Exception).<init>(String) line: not available
FileNotFoundException(IOException).<init>(String) line: not available
FileNotFoundException.<init>(String, String) line: not available
FileInputStream.open(String) line: not available [native method]
FileInputStream.<init>(File) line: not available
Toolkit$1.run() line: not available
AccessController.doPrivileged(PrivilegedAction<T>) line: not available [native method]
Toolkit.initAssistiveTechnologies() line: not available
Toolkit.<clinit>() line: not available
Component.<clinit>() line: not available
Main.main(String[]) line: 6
编辑 2:我已经找到了 JFileChooser
的哪一部分导致了问题:构造函数的第二个可选参数是 FileSystemView
哪个 bug 出来了。如果我自己写,它可以工作:
static public class DummyFSV extends FileSystemView
{
public SingleRootFileSystemView(File root)
{
super();
}
@Override
public File createNewFolder(File containingDir)
{
return null;
}
@Override
public File getDefaultDirectory()
{
return null;
}
@Override
public File getHomeDirectory()
{
return null;
}
@Override
public File[] getRoots()
{
return null;
}
}
...
JFileChooser = new JFileChooser( new DummyFVS() );
当然,我不能用它做太多事情。我通过 FileSystemView.getFileSystemView() 获取的默认 FSV 是 WindowsFileSystemView(适合我的操作系统),但一旦使用它就会出现 NPE。
虚拟 FSV 实际上会打开文件对话框,但我无法导航我的文件夹,因为它不是 Windows FSV。所以它的用途非常有限。
最佳答案
这是在普通 Windows 计算机上吗?哪个 Windows 版本?是否应用了任何注册表调整来更改资源管理器命名空间或“文件打开”对话框的 View ?
我看到过类似的问题,安装了第三方工具来尝试操纵“文件打开”对话框的 View ,这似乎会产生一些不一致的状态,导致在尝试获取“网上邻居”的路径时在 GetFileSystemPath 中导致 NullPointerException .
关于java - 创建 JFileChooser 对象时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943154/