最近项目碰到 要同步一个文件到另一台服务器。借用了前辈的工具类做了点修改。记录下来,方便以后查阅。
package com.sitech.billing.framework.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
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 SftpUploadFile {
/**
* 密码方式登录 sftp
* @param ip 服务器ip
* @param user 服务器用户名
* @param psw 服务器密码
* @param port 端口
* @param sPath 原始路径
* @param dPath 目标路径
* @throws Exception
*/
public static void sshSftp(String ip, String user, String psw, int port,
String sPath, String dPath) throws Exception {
System.out.println("password login");
Session session = null;
JSch jsch = new JSch();
if (port <= 0) {
// 连接服务器,采用默认端口
session = jsch.getSession(user, ip);
} else {
// 采用指定的端口连接服务器
session = jsch.getSession(user, ip, port);
}
// 如果服务器连接不上,则抛出异常
if (session == null) {
throw new Exception("session is null");
}
// 设置登陆主机的密码
session.setPassword(psw);// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 设置登陆超时时间
session.connect(300000);
Channel channel = (Channel) session.openChannel("sftp");
channel.connect(10000000);
ChannelSftp sftp = (ChannelSftp) channel;
//复制文件
upLoadFile(sftp,sPath,dPath);
System.out.println("success");
}
public static void upLoadFile(ChannelSftp sftp, String sPath, String dPath) {
Date date=new Date();
SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
File file = new File(sPath);
String pwd = null;
try {
pwd = sftp.pwd();
pwd += "/"+dPath;
sftp.cd(pwd);
} catch (SftpException e) {
e.printStackTrace();
}
System.out.println("正在复制文件:" + file.getAbsolutePath());
InputStream instream = null;
OutputStream outstream = null;
try {
//文件按规范命名
String upfilename = "0002_CJFF_" +format.format(date)+ ".txt";
outstream = sftp.put(upfilename);
instream = new FileInputStream(file);
byte b[] = new byte[1024];
int n;
try {
while ((n = instream.read(b)) != -1) {
outstream.write(b, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(pwd+"/"+upfilename+"文件复制完成");
} catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outstream.flush();
outstream.close();
instream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}