package com.teradata.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpTest {
public static void main(String[] args) {
// testUpload();
testDownload();
}
/**
* FTP上传单个文件测试
*/
public static void testUpload() {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
try {
ftpClient.connect("127.0.0.1");
ftpClient.login("admin", "123");
File srcFile = new File("C:\\new.gif");
fis = new FileInputStream(srcFile);
// 设置上传目录
ftpClient.changeWorkingDirectory("/admin/pic");
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile("3.gif", fis);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
/**
* FTP下载单个文件测试
*/
public static void testDownload1() {
FTPClient ftpClient = new FTPClient();
FileOutputStream fos = null;
try {
ftpClient.connect("127.0.0.1");
ftpClient.login("f1", "123456");
//String remoteFileName = "E:\\FTP\\Remote\\";
//fos = new FileOutputStream("E:/FTP/dfff.txt");
FTPFile[] fs = ftpClient.listFiles();
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
for (int i = 0; i < fs.length; i++) {
FTPFile ff = fs[i];
FileOutputStream outputStream = new FileOutputStream("E:/FTP/"+ff.getName());
//ff.getName().equals(fileName)
if (true) {
//String filename = fileName;
// 这个就就是弹出下载对话框的关键代码
/*response.setHeader("Content-disposition",
"attachment;filename="
+ URLEncoder.encode(filename, "utf-8"));*/
// 将文件保存到输出流outputStream中
ftpClient.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), outputStream);
outputStream.flush();
outputStream.close();
}
}
// ftpClient.changeWorkingDirectory(remoteFileName);
//ftpClient.retrieveFile(remoteFileName + "3333.txt", fos);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fos);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
public static void testDownload() {
FTPClient ftpClient = new FTPClient();
FileOutputStream fos = null;
try {
ftpClient.connect("127.0.0.1");
//登錄之後就是給用戶配置的默认地址
//对于window,假定配置了E://FTP,
//登录时服务端看到的登录的起始目录是/
ftpClient.login("f1", "123456");
String remoteFileName = "fff.txt";
fos = new FileOutputStream("E:/FTP/dfff.txt");
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFileName, fos);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fos);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
}
package com.teradata.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
public class BSFTPTest {
private String host;
private String username;
private String password;
private int port = 22;
private ChannelSftp sftp = null;
private Session sshSession = null;
public BSFTPTest() {
}
public BSFTPTest(String host, String username, String password, int port) {
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
public BSFTPTest(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
}
/**
* connect server via sftp
*/
public boolean connect() {
try {
JSch jsch = new JSch();
sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.setPort(21);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 关闭资源
*/
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
System.out.println("sftp is closed already");
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
System.out.println("sshSession is closed already");
}
}
}
/**
* 批量下载文件
*
* @param remotPath
* 远程下载目录(以路径符号结束)
* @param localPath
* 本地保存目录(以路径符号结束)
* @param fileFormat
* 下载文件格式(以特定字符开头,为空不做检验)
* @param del
* 下载后是否删除sftp文件
* @return
*/
public boolean batchDownLoadFile(String remotPath, String localPath,
String fileFormat, boolean del) {
try {
sftp.cd(remotPath);
//Vector v = listFiles(remotPath);
Vector v = sftp.ls(remotPath);
if (v.size() > 0) {
Iterator it = v.iterator();
while (it.hasNext()) {
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
if (fileFormat != null && !"".equals(fileFormat.trim())) {
if (filename.startsWith(fileFormat)) {
if (this.downloadFile(remotPath, filename,
localPath, filename) && del) {
deleteSFTP(remotPath, filename);
}
}
} else {
if (this.downloadFile(remotPath, filename,
localPath, filename) && del) {
deleteSFTP(remotPath, filename);
}
}
}
}
}
} catch (SftpException e) {
e.printStackTrace();
} finally {
this.disconnect();
}
return false;
}
/**
* 下载单个文件
*
* @param remotPath
* 远程下载目录(以路径符号结束)
* @param remoteFileName
* 下载文件名
* @param localPath
* 本地保存目录(以路径符号结束)
* @param localFileName
* 保存文件名
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName,
String localPath, String localFileName) {
try {
File file = new File(localPath + localFileName);
mkdirs(localPath + localFileName);
sftp.get(remoteFileName, new FileOutputStream(file));
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
/**
* 上传单个文件
*
* @param remotePath
* 远程保存目录
* @param remoteFileName
* 保存文件名
* @param localPath
* 本地上传目录(以路径符号结束)
* @param localFileName
* 上传的文件名
* @return
*/
public boolean uploadFile(String remotePath, String remoteFileName,
String localPath, String localFileName) {
FileInputStream in = null;
try {
createDir(remotePath);
File file = new File(localPath + localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 批量上传文件
*
* @param remotePath
* 远程保存目录
* @param localPath
* 本地上传目录(以路径符号结束)
* @param del
* 上传后是否删除本地文件
* @return
*/
public boolean bacthUploadFile(String remotePath, String localPath,
boolean del) {
try {
connect();
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1) {
if (this.uploadFile(remotePath, files[i].getName(),
localPath, files[i].getName()) && del) {
deleteFile(localPath + files[i].getName());
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
this.disconnect();
}
return false;
}
/**
* 删除本地文件
*
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
return file.delete();
}
/**
* 创建目录
*
* @param createpath
* @return
*/
public boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断目录是否存在
*
* @param directory
* @return
*/
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除stfp文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public void deleteSFTP(String directory, String deleteFile) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 如果目录不存在就创建目录
*
* @param path
*/
public void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists()) {
f.mkdirs();
}
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
public static void main(String[] args) {
String hosts = Constant.getStPara("hosts");
String user = Constant.getStPara("user");
String pwd = Constant.getStPara("pwd");
BSFTPTest ftp = new BSFTPTest(hosts,user,pwd);
String localPath = Constant.getStPara("localPath");
String remotePath = Constant.getStPara("remotePath");
ftp.connect();
ftp.batchDownLoadFile(remotePath, localPath, null, false);
ftp.disconnect();
System.exit(0);
}
}
package com.teradata.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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;
/**
*/
public class SFtpTest {
/**
* 连接sftp服务器
*
* @param host
* 主机
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
// sshConfig.put("PasswordAuthentication", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
} catch (Exception e) {
e.printStackTrace();
}
return sftp;
}
/**
* 上传文件
*
* @param directory
* 上传的目录
* @param uploadFile
* 要上传的文件
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
* @param sftp
*/
public void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp)
throws SftpException {
return sftp.ls(directory);
}
public static void main(String[] args) throws JSchException {
SFtpTest sf = new SFtpTest();
String host = "192.168.1.104";
int port = 22;
String username = "root";
String password = "root";
String directory = "/root/";
String downloadFile = "tdebg.jpg";
String saveFile = "E:/FTP/jjj.jpg";
ChannelSftp sftp = sf.connect(host, port, username, password);
// sf.upload(directory, uploadFile, sftp);
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
System.out.println("download file success, file:" + downloadFile);
} catch (SftpException e) {
e.printStackTrace();
}catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
// 如果没有sesstion的disconnect,程序不会退出
sftp.getSession().disconnect();
sftp.disconnect();
sftp.exit();
}
}
}