我正在尝试使用JSch将文件放入SFTP目录。
channelSftp.cd(destDir);
channelSftp.put(new FileInputStream(filePath), filePath.substring(filePath.lastIndexOf(File.separatorChar)));
但上面的代码将文件始终放在SFTP用户主目录而不是destDir
。例如,如果我在用户主目录下创建一个子目录test
并将destDir
设置为channelSftp.getHome()+"test"
,那么该文件仍然只是复制到用户主目录而不是test子目录。
我试图在destDir
(test
子目录)中列出文件,它显示test
目录下的所有文件/目录。
Vector<com.jcraft.jsch.ChannelSftp.LsEntry> vv = channelSftp.ls(destDir);
if(vv != null) {
for(int ii=0; ii<vv.size(); ii++){
Object obj=vv.elementAt(ii);
if(obj instanceof LsEntry){
System.out.println(((LsEntry)obj).getLongname());
}
}
}
有什么建议?我查看了权限(test
子目录与SFTP用户主目录具有完全相同的权限)。
filePath.substring(filePath.lastIndexOf(File.separatorChar))
结果甚至包括最后一个分隔符。
所以,如果你通过/home/user/file.txt
,你得到/file.txt
。这是一个绝对路径,因此忽略任何工作目录,并且您实际上总是写入根文件夹。
你想要filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1)
只获得file.txt
。
另见How do I get the file name from a String containing the Absolute file path?
这很好用!!
channel.connect();
try {
channel.mkdir("subdir");
} catch (Exception e) {
// ... do something if subdir already exists
}
// Then the trick !
channel.put(inputStream, "subdir" + "/" + "filename.ext");