java實(shí)現(xiàn)FTP文件上傳與文件下載
本文實(shí)例為大家分享了兩種java實(shí)現(xiàn)FTP文件上傳下載的方式,供大家參考,具體內(nèi)容如下
第一種方式:
package com.cloudpower.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
/**
* Java自帶的API對(duì)FTP的操作
* @Title:Ftp.java
* @author: 周玲斌
*/
public class Ftp {
/**
* 本地文件名
*/
private String localfilename;
/**
* 遠(yuǎn)程文件名
*/
private String remotefilename;
/**
* FTP客戶端
*/
private FtpClient ftpClient;
/**
* 服務(wù)器連接
* @param ip 服務(wù)器IP
* @param port 服務(wù)器端口
* @param user 用戶名
* @param password 密碼
* @param path 服務(wù)器路徑
* @author 周玲斌
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******連接服務(wù)器的兩種方法*******/
//第一種方法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二種方法
ftpClient = new FtpClient(ip);
ftpClient.login(user, password);
// 設(shè)置成2進(jìn)制傳輸
ftpClient.binary();
System.out.println("login success!");
if (path.length() != 0){
//把遠(yuǎn)程系統(tǒng)上的目錄切換到參數(shù)path所指定的目錄
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 關(guān)閉連接
* @author 周玲斌
* @date 2012-7-11
*/
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println("disconnect success");
} catch (IOException ex) {
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 上傳文件
* @param localFile 本地文件
* @param remoteFile 遠(yuǎn)程文件
* @author 周玲斌
* @date 2012-7-11
*/
public void upload(String localFile, String remoteFile) {
this.localfilename = localFile;
this.remotefilename = remoteFile;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//將遠(yuǎn)程文件加入輸出流中
os = ftpClient.put(this.remotefilename);
//獲取本地文件的輸入流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//創(chuàng)建一個(gè)緩沖區(qū)
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("upload success");
} catch (IOException ex) {
System.out.println("not upload");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 下載文件
* @param remoteFile 遠(yuǎn)程文件路徑(服務(wù)器端)
* @param localFile 本地文件路徑(客戶端)
* @author 周玲斌
* @date 2012-7-11
*/
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//獲取遠(yuǎn)程機(jī)器上的文件filename,借助TelnetInputStream把該文件傳送到本地。
is = ftpClient.get(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("download success");
} catch (IOException ex) {
System.out.println("not download");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String agrs[]) {
String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};
Ftp fu = new Ftp();
/*
* 使用默認(rèn)的端口號(hào)、用戶名、密碼以及根目錄連接FTP服務(wù)器
*/
fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");
//下載
for (int i = 0; i < filepath.length; i++) {
fu.download(filepath[i], localfilepath[i]);
}
String localfile = "E:\\號(hào)碼.txt";
String remotefile = "/temp/哈哈.txt";
//上傳
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}
這種方式?jīng)]啥可說(shuō)的,比較簡(jiǎn)單,也不存在中文亂碼的問(wèn)題。貌似有個(gè)缺陷,不能操作大文件,有興趣的朋友可以試試。
第二種方式:
public class FtpApche {
private static FTPClient ftpClient = new FTPClient();
private static String encoding = System.getProperty("file.encoding");
/**
* Description: 向FTP服務(wù)器上傳文件
*
* @Version1.0
* @param url
* FTP服務(wù)器hostname
* @param port
* FTP服務(wù)器端口
* @param username
* FTP登錄賬號(hào)
* @param password
* FTP登錄密碼
* @param path
* FTP服務(wù)器保存目錄,如果是根目錄則為“/”
* @param filename
* 上傳到FTP服務(wù)器上的文件名
* @param input
* 本地文件輸入流
* @return 成功返回true,否則返回false
*/
public static boolean uploadFile(String url, int port, String username,
String password, String path, String filename, InputStream input) {
boolean result = false;
try {
int reply;
// 如果采用默認(rèn)端口,可以使用ftp.connect(url)的方式直接連接FTP服務(wù)器
ftpClient.connect(url);
// ftp.connect(url, port);// 連接FTP服務(wù)器
// 登錄
ftpClient.login(username, password);
ftpClient.setControlEncoding(encoding);
// 檢驗(yàn)是否連接成功
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("連接失敗");
ftpClient.disconnect();
return result;
}
// 轉(zhuǎn)移工作目錄至指定目錄下
boolean change = ftpClient.changeWorkingDirectory(path);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (change) {
result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
if (result) {
System.out.println("上傳成功!");
}
}
input.close();
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* 將本地文件上傳到FTP服務(wù)器上
*
*/
public void testUpLoadFromDisk() {
try {
FileInputStream in = new FileInputStream(new File("E:/號(hào)碼.txt"));
boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", "哈哈.txt", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Description: 從FTP服務(wù)器下載文件
*
* @Version1.0
* @param url
* FTP服務(wù)器hostname
* @param port
* FTP服務(wù)器端口
* @param username
* FTP登錄賬號(hào)
* @param password
* FTP登錄密碼
* @param remotePath
* FTP服務(wù)器上的相對(duì)路徑
* @param fileName
* 要下載的文件名
* @param localPath
* 下載后保存到本地的路徑
* @return
*/
public static boolean downFile(String url, int port, String username,
String password, String remotePath, String fileName,
String localPath) {
boolean result = false;
try {
int reply;
ftpClient.setControlEncoding(encoding);
/*
* 為了上傳和下載中文文件,有些地方建議使用以下兩句代替
* new String(remotePath.getBytes(encoding),"iso-8859-1")轉(zhuǎn)碼。
* 經(jīng)過(guò)測(cè)試,通不過(guò)。
*/
// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
// conf.setServerLanguageCode("zh");
ftpClient.connect(url, port);
// 如果采用默認(rèn)端口,可以使用ftp.connect(url)的方式直接連接FTP服務(wù)器
ftpClient.login(username, password);// 登錄
// 設(shè)置文件傳輸類型為二進(jìn)制
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 獲取ftp登錄應(yīng)答代碼
reply = ftpClient.getReplyCode();
// 驗(yàn)證是否登陸成功
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
return result;
}
// 轉(zhuǎn)移到FTP服務(wù)器目錄至指定的目錄下
ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
// 獲取文件列表
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
ftpClient.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* 將FTP服務(wù)器上文件下載到本地
*
*/
public void testDownFile() {
try {
boolean flag = downFile("127.0.0.1", 21, "zlb",
"123", "/", "哈哈.txt", "D:/");
System.out.println(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FtpApche fa = new FtpApche();
fa.testDownFile();
}
}
這種方式的話需要注意中文亂碼問(wèn)題啦,如果你設(shè)置不恰當(dāng),有可能上傳的文件名會(huì)為亂碼,有的時(shí)候根本就上傳不上去,當(dāng)然,也不會(huì)跟你提示,因?yàn)樵揪蜎](méi)異常。在網(wǎng)上找了好多解答方案,眾說(shuō)紛紜,幾乎都是從一個(gè)版本拷貝過(guò)去的,也沒(méi)有經(jīng)過(guò)自己的真是檢驗(yàn)。為此,也吃了不少苦頭。大致分為以下兩種解決方案:
1、加上以下三句即可解決
ftpClient.setControlEncoding(“GBK”);
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
解答:經(jīng)過(guò)測(cè)試,根本上行不通,上述問(wèn)題依然存在
2、與上述方式有所類似,但我覺(jué)得這種方式更靠譜一點(diǎn)
首先,加上ftpClient.setControlEncoding(“GBK”);這一句,然后,將所有的中文進(jìn)行轉(zhuǎn)碼為“ISO-8859-1”格式,如下:
ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"iso-8859-1"));
解答:經(jīng)過(guò)測(cè)試,仍然行不通,之所以我說(shuō)此方式更靠譜一點(diǎn),請(qǐng)繼續(xù)往下看
首先我們來(lái)說(shuō)說(shuō)為什么要進(jìn)行轉(zhuǎn)碼:
因?yàn)樵贔TP協(xié)議里面,規(guī)定文件名編碼為iso-8859-1,所以目錄名或文件名需要轉(zhuǎn)碼。
接下來(lái)的問(wèn)題是,我們應(yīng)該將什么編碼轉(zhuǎn)換為此格式。因此,就有了第二種解決方案——把 GBK格式的轉(zhuǎn)換為ISO-8859-1格式。而且,有的人還說(shuō),必須得這么轉(zhuǎn)。其實(shí),之所以他們能這么說(shuō),我覺(jué)得完全是巧合。它的真正原理是,既然 FTP協(xié)議規(guī)定的編碼格式是“ISO-8859-1”,那么我們確實(shí)得將格式轉(zhuǎn)換一下,然后等服務(wù)器收到文件時(shí)再自動(dòng)轉(zhuǎn)換為系統(tǒng)自帶的編碼格式,因此,關(guān)鍵不是規(guī)定為什么格式,而是取決于FTP服務(wù)器的編碼格式。因此,如果FTP系統(tǒng)的編碼格式為“GBK”時(shí),第二種方式肯定會(huì)成功;但是,如果系統(tǒng)的編碼格式為“UTF-8”時(shí),那就會(huì)仍然出現(xiàn)亂碼啦。所以,我們只能通過(guò)代碼先獲取系統(tǒng)的編碼格式,然后通過(guò)此編碼格式轉(zhuǎn)換為ISO-8859-1的編碼格式。獲取方式如下:
private static String encoding = System.getProperty("file.encoding");
以上代碼均通過(guò)自己測(cè)試,望能為大家解決一下問(wèn)題!
相關(guān)文章
利用Jackson解決Json序列化和反序列化問(wèn)題
Jackson是一個(gè)用于處理Json數(shù)據(jù)的Java庫(kù),它提供了一系列功能,包括Json序列化和反序列化,所以本文就來(lái)講講如何利用利用Jackson解決Json序列化和反序列化的問(wèn)題吧2023-05-05
詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式
這篇文章主要介紹了詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
spring cloud學(xué)習(xí)教程之config修改配置詳解
這篇文章主要給大家介紹了關(guān)于spring cloud學(xué)習(xí)教程之config修改配置的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
java this 用法詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了java this 用法詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-03-03
elasticsearch節(jié)點(diǎn)間通信的基礎(chǔ)transport啟動(dòng)過(guò)程
這篇文章主要為大家介紹了elasticsearch節(jié)點(diǎn)間通信的基礎(chǔ)transport啟動(dòng)過(guò)程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(13)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07
淺析EasyExcel如何導(dǎo)出自動(dòng)回顯中文
這篇文章主要為大家詳細(xì)介紹了EasyExcel如何通過(guò)全局轉(zhuǎn)換器和自定義注解實(shí)現(xiàn)導(dǎo)出自動(dòng)回顯中文,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04

