JSch 将文件放入子目录
JSch put file into a subdirectory
我正在尝试使用 JSch 将文件放入 SFTP 目录。
channelSftp.cd(destDir);
channelSftp.put(new FileInputStream(filePath), filePath.substring(filePath.lastIndexOf(File.separatorChar)));
但上面的代码始终将文件放在 SFTP 用户主目录中,而不是 destDir
。例如,如果我在用户主目录下创建一个子目录 test
并将 destDir
设置为 channelSftp.getHome()+"test"
,文件仍然只复制到用户主目录而不是测试子目录。
我试图列出 destDir
(test
子目录)中的文件,它显示 test
目录下的所有 files/directories。
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");
我正在尝试使用 JSch 将文件放入 SFTP 目录。
channelSftp.cd(destDir);
channelSftp.put(new FileInputStream(filePath), filePath.substring(filePath.lastIndexOf(File.separatorChar)));
但上面的代码始终将文件放在 SFTP 用户主目录中,而不是 destDir
。例如,如果我在用户主目录下创建一个子目录 test
并将 destDir
设置为 channelSftp.getHome()+"test"
,文件仍然只复制到用户主目录而不是测试子目录。
我试图列出 destDir
(test
子目录)中的文件,它显示 test
目录下的所有 files/directories。
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");