我有一个问题,希望得到解决方案。我也写了一些代码,但它需要一些修改。
问题: 我有一个需要连接的 SFTP 服务器(出于隐私目的,我将提供虚拟凭据)。
服务器名称:服务器名称
端口:22
用户名:用户名
密码:密码
当我连接到服务器时,它会自动将我放到 /FGV
目录中。此目录内还有其他几个文件夹。我需要从 /FGV/US/BS/
目录中获取 xml 消息的 LIST,并将它们放入 LIST(文件形式的文件)中。在列表中,我需要有文件的目录、文件名和文件体。我正在考虑创建一个对象并将这些信息放在那里并创建该对象的列表。
我当前的代码创建一个连接并只下载一个 xml 文件。如果有两个 xml 文件,那么我本地机器上的文件没有任何内容。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SFTPinJava {
public SFTPinJava() {
}
public static void main(String[] args) {
String SFTPHOST = "server-name";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "/FGV";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(
channelSftp.get("/FGV/US/BS/FGVCustomsEntryLoaderService.xml"));
File newFile = new File(
"C:\\workspace\\Crap\\src\\org\\raghav\\stuff\\XML_FROM_SERVER.xml");
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
//System.out.println("Getting: " + theLine);
while ((readCount = bis.read(buffer)) > 0) {
//System.out.println("Writing: ");
bos.write(buffer, 0, readCount);
}
while(session != null){
System.out.println("Killing the session");
session.disconnect();
bis.close();
bos.close();
System.exit(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我需要更改此代码,以便它可以抓取多个文件并将它们放入对象列表中。该对象应具有文件目录、文件名和文件正文。
最佳答案
您可以使用
列出给定目录中的所有文件Vector<ChannelSftp.LsEntry> list = channelSftp.ls("*.csv");
for(ChannelSftp.LsEntry entry : list) {
System.out.println(entry.getFilename());
}
在
之后添加这段代码channelSftp.cd(SFTPWORKINGDIR);
现在您将获得文件对象列表。文件对象是条目。如果你想下载所有文件。将此代码添加到 for 循环中。
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(channelSftp.get(entry.getFilename()));
File newFile = new File("C:/Users/Desktop/sftpStuff/"+entry.getFilename());
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
//System.out.println("Getting: " + theLine);
while( (readCount = bis.read(buffer)) > 0) {
System.out.println("Writing: "+entry.getFilename() );
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
关于java - 如何从 SFTP 服务器获取文件列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878209/