【发布时间】:2020-03-22 10:00:24
【问题描述】:
我正在尝试用 java 编写代码来检查远程服务器上是否存在目录。我尝试了Check whether the path exists on server or not in Java 上提到的一些东西。
ChannelSftp channelSftp = new ChannelSftp();
SftpATTRS attrs = null;
try {
String currentDirectory = channelSftp.pwd();
System.out.println(currentDirectory);
} catch (SftpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
attrs = channelSftp.stat("/x/web/STAGE2MA49/qatools/capturescripts_new");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(" not found");
}
但是上面的代码确实成功了。下面是错误堆栈
at com.jcraft.jsch.ChannelSftp.getHome(ChannelSftp.java:2443)
at com.jcraft.jsch.ChannelSftp.getCwd(ChannelSftp.java:2452)
at com.jcraft.jsch.ChannelSftp.pwd(ChannelSftp.java:2429)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:336)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:113)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:206)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:177)
Caused by: java.lang.NullPointerException
at com.jcraft.jsch.ChannelSftp.getHome(ChannelSftp.java:2435)
... 21 more
【问题讨论】:
-
“但确实成功了。得到空指针异常”应该是“...没有成功了...”。无论如何 NullPointerException 是 very common problem 但没有 minimal reproducible example 我们无法帮助您进行调试。
-
我的猜测是,由于未找到路径
SftpATTRS attrs = null;保持为null所以后来涉及它的操作,如attrs.someMethod();最终会调用null.someMethod();但null没有任何方法并抛出 NPE。要么执行依赖于try部分中的attrs值的代码,该部分为它分配非空值,或者每次使用它时检查它是否像if(attrs != null)那样不为空,或者不要将其包装在 @987654334 @ 并将您遇到的任何异常重新抛出给执行您的代码的客户,然后他将不得不决定如何处理此类异常。