java sftp tools

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;

public class Sftp {
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
JSch jsch = new JSch();
try {
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
return sftp;
}

public void downLoadFolder(String sftpdirectory, String localdirectory,
ChannelSftp sftp) throws FileNotFoundException {
try {
Vector vector = sftp.ls(sftpdirectory);
Iterator it = vector.iterator();
while (it.hasNext()) {
LsEntry ls = (LsEntry) it.next();
sftp.cd(sftpdirectory);
new File(localdirectory);
File file = new File(localdirectory + "\\" + ls.getFilename());
if (!file.isDirectory()) {
sftp.get(ls.getFilename(), new FileOutputStream(file));
}
}
} catch (SftpException e) {
e.printStackTrace();
}
}

public void upload(String sftpdirectory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(sftpdirectory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}

public void disconnect(ChannelSftp sftp) {
if (sftp.isConnected()) {
try {
sftp.disconnect();
sftp.getSession().disconnect();
sftp.exit();
} catch (JSchException e) {
e.printStackTrace();
}

}
}

}

你可能感兴趣的:(java)