[英]Code in java to check if a directory exists or not on remote server
我正在尝试用 java 编写代码来检查远程服务器上是否存在目录。 我已经尝试了检查服务器上是否存在 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
ChannelSftp channelSftp = new ChannelSftp();
您不能仅仅构造一个ChannelSftp
对象并期望它工作。 您需要创建一个到远程服务器的 SSH 会话,然后请求一个 SFTP 通道来运行该会话。
您链接到的问题引用了一个示例程序,该程序使用 Jsch 与远程服务器建立 SFTP 连接。 我将在这里重现其中的一部分:
JSch jsch=new JSch();
...
Session session=jsch.getSession(user, host, port);
...
session.connect();
...
Channel channel=session.openChannel("sftp");
channel.connect();
ChannelSftp c=(ChannelSftp)channel;
使用 JSCH API,您将创建一个Jsch
对象,然后使用它来创建一个Session
,然后使用Session
对象连接到远程服务器。 假设有效,您可以请求通过会话运行的“sftp”通道。 这将返回您需要的ChannelSftp
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.