java搭建ftp/sftp進行數(shù)據(jù)傳遞的全過程
ftp/sftp概念及搭建
ftp是一種文件傳輸協(xié)議,讓客戶端和服務端能夠互相傳遞文件,圖片等數(shù)據(jù);方便快捷;
sftp是ssh file transfer protocol縮寫,也是一種文件傳輸協(xié)議.sftp比ftp安全的多,但傳輸效率要低的多
搭建:
ftp可以搜索網(wǎng)上教程,很多,在此不過多贅述

創(chuàng)建完成后,通過瀏覽器就可以訪問到內(nèi)容了;
sftp用freesshd搭建(記得freesshd的安裝路徑不要有中文,否則各種報錯);這個也可以自行百度,解決方法很多;
Java代碼
代碼如下:
import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
public class FTPClientTest
{
private static String userName; // FTP 登錄用戶名
private static String password; // FTP 登錄密碼
private static String ip;// FTP 服務器地址IP地址
private static int port; // FTP 端口
//構(gòu)造函數(shù)初始化
public FTPClientTest(String userName,String password,String ip,int port){
this.userName=userName;
this.password=password;
this.ip=ip;
this.port=port;
}
public static String getUserName(){ return userName;}
public static void setUserName(String userName) {FTPClientTest.userName = userName; }
public static String getPassword() {return password;}
public static void setPassword(String password){FTPClientTest.password = password;}
public static String getIp() { return ip; }
public static void setIp(String ip){FTPClientTest.ip = ip;}
public static int getPort() {return port; }
public static void setPort(int port) {FTPClientTest.port = port;}
private static FTPClient ftpClient = null; // FTP 客戶端代理
/**
* 連接到服務器
* @return true 連接服務器成功,false 連接服務器失敗
*/
public boolean connectServer()
{
System.out.println("進行連接");
boolean flag = true;
if (ftpClient == null)
{
int reply;
try
{
System.out.println("初始化連接");
ftpClient = new FTPClient();
String LOCAL_CHARSET = "GBK";
System.out.println("設置IP和端口");
ftpClient.connect(ip, port);
System.out.println("設置密碼");
ftpClient.login(userName, password);
System.out.println("進行連接");
reply = ftpClient.getReplyCode();
ftpClient.setDataTimeout(120000);
System.out.println("設置編碼操作方式");
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) // 開啟服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK).
{
LOCAL_CHARSET = "UTF-8";
}
System.out.println("設置編碼操作方式1");
ftpClient.setControlEncoding(LOCAL_CHARSET);
System.out.println("是否連接成功");
if (!FTPReply.isPositiveCompletion(reply))
{
ftpClient.disconnect();
System.out.println("FTP 服務拒絕連接!");
flag = false;
}
}
catch (SocketException e)
{
flag = false;
e.printStackTrace();
System.out.println("登錄ftp服務器 " + ip + " 失敗,連接超時!");
}
catch (IOException e)
{
flag = false;
e.printStackTrace();
System.out.println("登錄ftp服務器 " + ip + " 失敗,F(xiàn)TP服務器無法打開!");
}
catch (Exception e)
{
flag = false;
e.printStackTrace();
// System.out.println("登錄ftp服務器 " + ip + " 失敗,F(xiàn)TP服務器無法打開!");
}
}
return flag;
}
/**
* 上傳文件
*
* @param remoteFile 遠程文件路徑,支持多級目錄嵌套 需要保證路徑已經(jīng)存在 并切包含文件重命名
* @param localFile 本地文件名稱,絕對路徑
*
*/
public boolean uploadFile(String remoteFile1, File localFile)
{
boolean flag = false;
try
{
InputStream in = new FileInputStream(localFile);
String remote = new String(remoteFile1.getBytes("UTF-8"), "iso-8859-1");
if (ftpClient.storeFile(remote, in))
{
flag = true;
System.out.println(localFile.getAbsolutePath() + "上傳文件成功!");
}
else
{
System.out.println(localFile.getAbsolutePath() + "上傳文件失?。?);
}
in.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
/**
* 上傳單個文件
*
* @param local 本地文件名稱,絕對路徑
* @param remote 遠程文件路徑,支持多級目錄嵌套
* @return
*/
public boolean uploadFile(String local, String remote)
{
boolean flag = true;
String remoteFileName = remote;
if (remote.contains("/"))
{
remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
// 創(chuàng)建服務器遠程目錄結(jié)構(gòu),創(chuàng)建失敗直接返回
if (!CreateDirecroty(remote))
{
return false;
}
}
File f = new File(local);
if (!uploadFile(remoteFileName, f))
{
flag = false;
}
return flag;
}
/**
* 上傳文件夾內(nèi)的所有文件
*
*
* @param filename 本地文件夾絕對路徑 只能上傳文件,子文件夾無法上傳
* @param uploadpath 上傳到FTP的路徑,形式為/或/dir1/dir2/../
* @return true 上傳成功,false 上傳失敗
* @throws IOException
*/
public ArrayList<String> uploadManyFile(String filename, String uploadpath)
{
boolean flag = true;
ArrayList<String> l = new ArrayList<String>();
StringBuffer strBuf = new StringBuffer();
int n = 0; // 上傳失敗的文件個數(shù)
int m = 0; // 上傳成功的文件個數(shù)
try
{
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
ftpClient.changeWorkingDirectory("/");
File file = new File(filename);
File fileList[] = file.listFiles();
for (File upfile : fileList)
{
if (!upfile.isDirectory())
{
String local = upfile.getCanonicalPath().replaceAll("\\\\", "/");
String temp = upfile.getCanonicalPath();
String a = temp.replace(filename + "\\", "");
String remote = uploadpath.replaceAll("\\\\", "/") + a;
flag = uploadFile(local, remote);
ftpClient.changeWorkingDirectory("/");
}
if (!flag)
{
n++;
strBuf.append(upfile.getName() + ",");
System.out.println("文件[" + upfile.getName() + "]上傳失敗");
}
else
{
m++;
}
}
l.add("失敗個數(shù)" + n);
l.add("成功個數(shù)" + m);
l.add(strBuf.toString());
}
catch (NullPointerException e)
{
e.printStackTrace();
System.out.println("本地文件上傳失??!找不到上傳文件!" + e);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("本地文件上傳失?。? + e);
}
return l;
}
/**
* 下載文件
*
* @param remoteFileName --服務器上的文件名
* @param localFileName--本地文件名
* @return true 下載成功,false 下載失敗
*/
public boolean loadFile(String remoteFileName, String localFileName)
{
boolean flag = true;
// 下載文件
BufferedOutputStream buffOut = null;
try
{
buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), buffOut);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("本地文件下載失?。? + e);
}
finally
{
try
{
if (buffOut != null)
buffOut.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return flag;
}
/**
* 刪除一個文件
*/
public boolean deleteFile(String filename)
{
boolean flag = true;
try
{
flag = ftpClient.deleteFile(new String(filename.getBytes("UTF-8"), "iso-8859-1"));
if (flag)
{
System.out.println("刪除文件" + filename + "成功!");
}
else
{
System.out.println("刪除文件" + filename + "成功!");
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return flag;
}
/**
* 刪除空目錄
*/
public void deleteEmptyDirectory(String pathname)
{
try
{
ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"), "iso-8859-1"));
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
/**
* 列出Ftp服務器上的所有文件和目錄
*/
public String[] listRemoteAllFiles()
{
try
{
String[] names = ftpClient.listNames();
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i]);
}
return names;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 關閉連接
*/
public void closeConnect()
{
try
{
if (ftpClient != null)
{
ftpClient.logout();
ftpClient.disconnect();
ftpClient=null;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 設置傳輸文件的類型[文本文件或者二進制文件] 1是文本文件 其余 二進制文件
*
* @param fileType--BINARY_FILE_TYPE(二進制文件)、ASCII_FILE_TYPE(文本文件)
*
*/
public void setFileType(int fileType1)
{
try
{
int a = FTP.BINARY_FILE_TYPE;
if (fileType1 == 1)
{
a = FTP.ASCII_FILE_TYPE;
}
ftpClient.setFileType(a);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 進入到服務器的某個目錄下
*
* @param directory
*/
public boolean changeWorkingDirectory(String directory)
{
boolean flag = true;
try
{
flag = ftpClient.changeWorkingDirectory(directory);
if (flag)
{
System.out.println("進入文件夾" + directory + " 成功!");
}
else
{
System.out.println("進入文件夾" + directory + " 失?。?);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return flag;
}
/**
* 返回到上一層目錄
*/
public void changeToParentDirectory()
{
try
{
ftpClient.changeToParentDirectory();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
/**
* 重命名文件
*
* @param oldFileName --原文件名
* @param newFileName --新文件名
*/
public void renameFile(String oldFileName, String newFileName)
{
try
{
System.out.println(oldFileName);
System.out.println(newFileName);
ftpClient.rename(new String(oldFileName.getBytes("UTF-8"), "iso-8859-1"), new String(newFileName.getBytes("UTF-8"), "iso-8859-1"));
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 設置FTP客服端的配置--一般可以不設置
*
* @return ftpConfig
*/
@SuppressWarnings("unused")
private FTPClientConfig getFtpConfig()
{
FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
return ftpConfig;
}
/**
* 轉(zhuǎn)碼[ISO-8859-1 -> GBK] 不同的平臺需要不同的轉(zhuǎn)碼
*
* @param obj
* @return ""
*/
@SuppressWarnings("unused")
private String iso8859togbk(Object obj)
{
try
{
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
}
catch (Exception e)
{
return "";
}
}
/**
* 在服務器上創(chuàng)建一個文件夾
*
* @param dir 文件夾名稱,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...
*/
public boolean makeDirectory(String dir)
{
boolean flag = true;
try
{
flag = ftpClient.makeDirectory(dir);
if (flag)
{
System.out.println("創(chuàng)建文件夾" + dir + " 成功!");
}
else
{
System.out.println("創(chuàng)建文件夾" + dir + " 失??!");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return flag;
}
/**
* 遞歸創(chuàng)建遠程服務器目錄
*
* @param remote 遠程服務器文件絕對路徑 路徑: /Draw1/Point1/GUID1/a.bmp 或者/Draw1/Point1/GUID1/ 最后一級文件夾必須有/否則最后一級文件夾創(chuàng)建不成功
*
* @return 目錄創(chuàng)建是否成功
* @throws IOException
*/
public boolean CreateDirecroty(String remote)
{
boolean success = true;
try
{
String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
// 如果遠程目錄不存在,則遞歸創(chuàng)建遠程服務器目錄
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory)))
{
int start = 0;
int end = 0;
if (directory.startsWith("/"))
{
start = 1;
}
else
{
start = 0;
}
end = directory.indexOf("/", start);
while (true)
{
String subDirectory;
subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
if (!changeWorkingDirectory(subDirectory))
{
if (makeDirectory(subDirectory))
{
changeWorkingDirectory(subDirectory);
}
else
{
System.out.println("創(chuàng)建目錄[" + subDirectory + "]失敗");
System.out.println("創(chuàng)建目錄[" + subDirectory + "]失敗");
success = false;
return success;
}
}
start = end + 1;
end = directory.indexOf("/", start);
// 檢查所有目錄是否創(chuàng)建完畢
if (end <= start)
{
break;
}
}
}
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return success;
}
}
ftp測試代碼如下:
public class test {
public static void main(String[] args) {
FTPClientTest ftp=new FTPClientTest("user", "548", "168.125.256.22", 21);
boolean b=ftp.connectServer();
System.out.println(b);
System.out.println(ftp.listRemoteAllFiles());
System.out.println(ftp.uploadFile("F:/home/b.txt", "/c.txt"));
System.out.println(ftp.loadFile("/a.txt", "F:/home/b.txt"));
ftp.closeConnect();
}
}
輸出結(jié)果如下:

成功了;
sftp搭建完成后,也測試下,至于搭建過程,自行百度好啦

看到?jīng)],連接成功了;我用我的電腦模擬的;
相關文章
IDEA的Terminal無法執(zhí)行g(shù)it命令問題
這篇文章主要介紹了IDEA的Terminal無法執(zhí)行g(shù)it命令問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
mybatis Example的Criteria用法:or與isNull詳解
這篇文章主要介紹了mybatis Example的Criteria用法:or與isNull詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
簡述Java中進程與線程的關系_動力節(jié)點Java學院整理
在 Java 語言中,對進程和線程的封裝,分別提供了 Process 和 Thread 相關的一些類。本文首先簡單的介紹如何使用這些類來創(chuàng)建進程和線程2017-05-05
解決IntelliJ IDEA 控制臺輸出中文亂碼問題(史上最簡單)
這篇文章主要介紹了史上最簡單的IntelliJ IDEA 控制臺輸出中文亂碼問題的解決方法,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-05-05
springboot使用webservice發(fā)布和調(diào)用接口的實例詳解
本文介紹了如何在Springboot中使用webservice發(fā)布和調(diào)用接口,涵蓋了必要的依賴添加和代碼示例,文中提供了服務端和客戶端的實現(xiàn)方法,以及如何設置端口和服務地址,幫助讀者更好地理解和應用Springboot結(jié)合webservice的技術(shù)2024-10-10
Java實現(xiàn)將PDF轉(zhuǎn)為PDF/A
通過將PDF格式轉(zhuǎn)換為PDF/A格式,可保護文檔布局、格式、字體、大小等不受更改,從而實現(xiàn)文檔安全保護的目的,同時又能保證文檔可讀、可訪問。本文將為大家介紹如何實現(xiàn)這一轉(zhuǎn)換,需要的可以參考一下2022-01-01
Spring Jpa多數(shù)據(jù)源工程配置過程解析
這篇文章主要介紹了Spring Jpa多數(shù)據(jù)源工程配置過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08

