}
二:
package com.files.upload;
/**
* 定义常量
* @author Frank.dai
*
*/
public class SFTPConstants {
public static final String SFTP_REQ_HOST = "host";
public static final String SFTP_REQ_PORT = "port";
public static final String SFTP_REQ_USERNAME = "username";
public static final String SFTP_REQ_PASSWORD = "password";
public static final int SFTP_DEFAULT_PORT = 22;
public static final String SFTP_REQ_LOC = "location";
}
三:
package com.files.upload;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.jcraft.jsch.ChannelSftp;
public class SFTPTest {
public SFTPChannel getSFTPChannel() {
return new SFTPChannel();
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
InputStream in = Thread.currentThread().getClass().getResourceAsStream("/database.properties");
properties.load(in);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, Integer.valueOf(properties.getProperty("indexday")));
String yesteDay = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
SFTPTest test = new SFTPTest();
Map
// 设置主机ip,端口,用户名,密码
sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "10.1.234.23");
sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "dwaml");
sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "1234qwer");
sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");
SFTPChannel channel = test.getSFTPChannel();
ChannelSftp chSftp = channel.getChannel(sftpDetails, 60000);
String pathINV = properties.getProperty("pathINV");
String filePath = pathINV + yesteDay;
String a = "/home/adb/JKLIFE/INVEST/";
String dst = a+yesteDay; // 目标文件名
int countDirectory = 0;//文件个数
File folder = new File(filePath); // 自定义文件路径
if(folder.exists() && folder.isDirectory()){
File files[] = folder.listFiles();
for(File fileIndex : files){
countDirectory++;
String src = fileIndex.toString();
chSftp.put(src, dst, ChannelSftp.OVERWRITE); // 代码段2
System.out.println(countDirectory);
System.out.println("上传成功");
}
}else{
System.out.println("文件不存在");
}
chSftp.quit();
channel.closeChannel();
/**
* 代码段1
OutputStream out = chSftp.put(dst, ChannelSftp.OVERWRITE); // 使用OVERWRITE模式
byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB
int read;
if (out != null) {
System.out.println("Start to read input stream");
InputStream is = new FileInputStream(src);
do {
read = is.read(buff, 0, buff.length);
if (read > 0) {
out.write(buff, 0, read);
}
out.flush();
} while (read >= 0);
System.out.println("input stream read done.");
}
**/
/* chSftp.put(src, dst, ChannelSftp.OVERWRITE); // 代码段2
// chSftp.put(new FileInputStream(src), dst, ChannelSftp.OVERWRITE); // 代码段3
// chSftp.put(new FileInputStream(src), dst, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); // 代码段3
System.out.println("上传成功");
chSftp.quit();
channel.closeChannel();*/
}
}