Java8实现FTP及SFTP文件上传下载
有网上的代码,也有自己的理解,代码备份
一般连接windows服务器使用FTP,连接linux服务器使用SFTP。linux都是通过SFTP上传文件,不需要额外安装,非要使用FTP的话,还得安装FTP服务(虽然刚开始我就是这么干的)。
另外就是jdk1.8和jdk1.7之前的方法有些不同,网上有很多jdk1.7之前的介绍,本篇是jdk1.8的
添加依赖Jsch-0.1.54.jar
com.jcraft jsch 0.1.54
FTP上传下载文件例子
importsun.net.ftp.FtpClient;
importsun.net.ftp.FtpProtocolException;
importjava.io.*;
importjava.net.InetSocketAddress;
importjava.net.SocketAddress;
/**
*Java自带的API对FTP的操作
*/
publicclassTest{
privateFtpClientftpClient;
Test(){
/*
使用默认的端口号、用户名、密码以及根目录连接FTP服务器
*/
this.connectServer("192.168.56.130",21,"jiashubing","123456","/home/jiashubing/ftp/anonymous/");
}
publicvoidconnectServer(Stringip,intport,Stringuser,Stringpassword,Stringpath){
try{
/*******连接服务器的两种方法*******/
ftpClient=FtpClient.create();
try{
SocketAddressaddr=newInetSocketAddress(ip,port);
ftpClient.connect(addr);
ftpClient.login(user,password.toCharArray());
System.out.println("loginsuccess!");
if(path.length()!=0){
//把远程系统上的目录切换到参数path所指定的目录
ftpClient.changeDirectory(path);
}
}catch(FtpProtocolExceptione){
e.printStackTrace();
}
}catch(IOExceptionex){
ex.printStackTrace();
thrownewRuntimeException(ex);
}
}
/**
*关闭连接
*/
publicvoidcloseConnect(){
try{
ftpClient.close();
System.out.println("disconnectsuccess");
}catch(IOExceptionex){
System.out.println("notdisconnect");
ex.printStackTrace();
thrownewRuntimeException(ex);
}
}
/**
*上传文件
*@paramlocalFile本地文件
*@paramremoteFile远程文件
*/
publicvoidupload(StringlocalFile,StringremoteFile){
Filefile_in=newFile(localFile);
try(OutputStreamos=ftpClient.putFileStream(remoteFile);
FileInputStreamis=newFileInputStream(file_in)){
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
}
System.out.println("uploadsuccess");
}catch(IOExceptionex){
System.out.println("notupload");
ex.printStackTrace();
}catch(FtpProtocolExceptione){
e.printStackTrace();
}
}
/**
*下载文件。获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
*@paramremoteFile远程文件路径(服务器端)
*@paramlocalFile本地文件路径(客户端)
*/
publicvoiddownload(StringremoteFile,StringlocalFile){
Filefile_in=newFile(localFile);
try(InputStreamis=ftpClient.getFileStream(remoteFile);
FileOutputStreamos=newFileOutputStream(file_in)){
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
}
System.out.println("downloadsuccess");
}catch(IOExceptionex){
System.out.println("notdownload");
ex.printStackTrace();
}catch(FtpProtocolExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(Stringagrs[]){
Testfu=newTest();
//下载测试
Stringfilepath[]={"aa.xlsx","bb.xlsx"};
Stringlocalfilepath[]={"E:/lalala/aa.xlsx","E:/lalala/bb.xlsx"};
for(inti=0;i
SFTP上传下载文件例子
importcom.jcraft.jsch.*;
importjava.util.Properties;
/**
*解释一下SFTP的整个调用过程,这个过程就是通过Ip、Port、Username、Password获取一个Session,
*然后通过Session打开SFTP通道(获得SFTPChannel对象),再在建立通道(Channel)连接,最后我们就是
*通过这个Channel对象来调用SFTP的各种操作方法.总是要记得,我们操作完SFTP需要手动断开Channel连接与Session连接。
*@authorjiashubing
*@since2018/5/8
*/
publicclassSftpCustom{
privateChannelSftpchannel;
privateSessionsession;
privateStringsftpPath;
SftpCustom(){
/*
使用端口号、用户名、密码以连接SFTP服务器
*/
this.connectServer("192.168.56.130",22,"jiashubing","123456","/home/ftp/");
}
SftpCustom(StringftpHost,intftpPort,StringftpUserName,StringftpPassword,StringsftpPath){
this.connectServer(ftpHost,ftpPort,ftpUserName,ftpPassword,sftpPath);
}
publicvoidconnectServer(StringftpHost,intftpPort,StringftpUserName,StringftpPassword,StringsftpPath){
try{
this.sftpPath=sftpPath;
//创建JSch对象
JSchjsch=newJSch();
//根据用户名,主机ip,端口获取一个Session对象
session=jsch.getSession(ftpUserName,ftpHost,ftpPort);
if(ftpPassword!=null){
//设置密码
session.setPassword(ftpPassword);
}
PropertiesconfigTemp=newProperties();
configTemp.put("StrictHostKeyChecking","no");
//为Session对象设置properties
session.setConfig(configTemp);
//设置timeout时间
session.setTimeout(60000);
session.connect();
//通过Session建立链接
//打开SFTP通道
channel=(ChannelSftp)session.openChannel("sftp");
//建立SFTP通道的连接
channel.connect();
}catch(JSchExceptione){
//thrownewRuntimeException(e);
}
}
/**
*断开SFTPChannel、Session连接
*/
publicvoidcloseChannel(){
try{
if(channel!=null){
channel.disconnect();
}
if(session!=null){
session.disconnect();
}
}catch(Exceptione){
//
}
}
/**
*上传文件
*
*@paramlocalFile本地文件
*@paramremoteFile远程文件
*/
publicvoidupload(StringlocalFile,StringremoteFile){
try{
remoteFile=sftpPath+remoteFile;
channel.put(localFile,remoteFile,ChannelSftp.OVERWRITE);
channel.quit();
}catch(SftpExceptione){
//e.printStackTrace();
}
}
/**
*下载文件
*
*@paramremoteFile远程文件
*@paramlocalFile本地文件
*/
publicvoiddownload(StringremoteFile,StringlocalFile){
try{
remoteFile=sftpPath+remoteFile;
channel.get(remoteFile,localFile);
channel.quit();
}catch(SftpExceptione){
//e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
SftpCustomsftpCustom=newSftpCustom();
//上传测试
Stringlocalfile="E:/lalala/tt.xlsx";
Stringremotefile="/home/ftp/tt2.xlsx";
sftpCustom.upload(localfile,remotefile);
//下载测试
sftpCustom.download(remotefile,"E:/lalala/tt3.xlsx");
sftpCustom.closeChannel();
}
}
Jsch-0.1.54.jar学习了解
ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:
文件上传put(),
文件下载get(),
进入指定目录cd().
得到指定目录下的文件列表ls().
重命名指定文件或目录rename().
删除指定文件rm(),创建目录mkdir(),删除目录rmdir().
大家引用方法时可以快速参考一下,具体传参需参考源码~
最后还要提一下的就是JSch支持的三种文件传输模式:
●APPEND追加模式,如果目标文件已存在,传输的文件将在目标文件后追加。
●RESUME恢复模式,如果文件已经传输一部分,这时由于网络或其他任何原因导致文件传输中断,如果下一次传输相同的文件,则会从上一次中断的地方续传。
●OVERWRITE完全覆盖模式,这是JSch的默认文件传输模式,即如果目标文件已经存在,传输的文件将完全覆盖目标文件,产生新的文件。
FTP和SFTP区别
FTP是一种文件传输协议,一般是为了方便数据共享的。包括一个FTP服务器和多个FTP客户端。FTP客户端通过FTP协议在服务器上下载资源。而SFTP协议是在FTP的基础上对数据进行加密,使得传输的数据相对来说更安全。但是这种安全是以牺牲效率为代价的,也就是说SFTP的传输效率比FTP要低(不过现实使用当中,没有发现多大差别)。个人肤浅的认为就是:一;FTP要安装,SFTP不要安装。二;SFTP更安全,但更安全带来副作用就是的效率比FTP要低些。
建议使用sftp代替ftp。
主要因为:
1、可以不用额外安装任何服务器端程序
2、会更省系统资源。
3、SFTP使用加密传输认证信息和传输数据,相对来说会更安全。
4、也不需要单独配置,对新手来说比较简单(开启SSH默认就开启了SFTP)。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。