java完成FTP文件上傳與文件下載。本站提示廣大學習愛好者:(java完成FTP文件上傳與文件下載)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成FTP文件上傳與文件下載正文
本文實例為年夜家分享了兩種java完成FTP文件上傳下載的方法,供年夜家參考,詳細內容以下
第一種方法:
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對FTP的操作
* @Title:Ftp.java
* @author: 周玲斌
*/
public class Ftp {
/**
* 當地文件名
*/
private String localfilename;
/**
* 長途文件名
*/
private String remotefilename;
/**
* FTP客戶端
*/
private FtpClient ftpClient;
/**
* 辦事器銜接
* @param ip 辦事器IP
* @param port 辦事器端口
* @param user 用戶名
* @param password 暗碼
* @param path 辦事器途徑
* @author 周玲斌
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******銜接辦事器的兩種辦法*******/
//第一種辦法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二種辦法
ftpClient = new FtpClient(ip);
ftpClient.login(user, password);
// 設置成2進制傳輸
ftpClient.binary();
System.out.println("login success!");
if (path.length() != 0){
//把長途體系上的目次切換到參數path所指定的目次
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 封閉銜接
* @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 長途文件
* @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 {
//將長途文件參加輸入流中
os = ftpClient.put(this.remotefilename);
//獲得當地文件的輸出流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//創立一個緩沖區
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 長途文件途徑(辦事器端)
* @param localFile 當地文件途徑(客戶端)
* @author 周玲斌
* @date 2012-7-11
*/
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//獲得長途機械上的文件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();
/*
* 應用默許的端標語、用戶名、暗碼和根目次銜接FTP辦事器
*/
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:\\號碼.txt";
String remotefile = "/temp/哈哈.txt";
//上傳
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}
這類方法沒啥可說的,比擬簡略,也不存在中文亂碼的成績。貌似有個缺點,不克不及操作年夜文件,有興致的同伙可以嘗嘗。
第二種方法:
public class FtpApche {
private static FTPClient ftpClient = new FTPClient();
private static String encoding = System.getProperty("file.encoding");
/**
* Description: 向FTP辦事器上傳文件
*
* @Version1.0
* @param url
* FTP辦事器hostname
* @param port
* FTP辦事器端口
* @param username
* FTP登錄賬號
* @param password
* FTP登錄暗碼
* @param path
* FTP辦事器保留目次,假如是根目次則為“/”
* @param filename
* 上傳到FTP辦事器上的文件名
* @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;
// 假如采取默許端口,可使用ftp.connect(url)的方法直接銜接FTP辦事器
ftpClient.connect(url);
// ftp.connect(url, port);// 銜接FTP辦事器
// 登錄
ftpClient.login(username, password);
ftpClient.setControlEncoding(encoding);
// 磨練能否銜接勝利
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("銜接掉敗");
ftpClient.disconnect();
return result;
}
// 轉移任務目次至指定目次下
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辦事器上
*
*/
public void testUpLoadFromDisk() {
try {
FileInputStream in = new FileInputStream(new File("E:/號碼.txt"));
boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", "哈哈.txt", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Description: 從FTP辦事器下載文件
*
* @Version1.0
* @param url
* FTP辦事器hostname
* @param port
* FTP辦事器端口
* @param username
* FTP登錄賬號
* @param password
* FTP登錄暗碼
* @param remotePath
* FTP辦事器上的絕對途徑
* @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")轉碼。
* 經由測試,通不外。
*/
// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
// conf.setServerLanguageCode("zh");
ftpClient.connect(url, port);
// 假如采取默許端口,可使用ftp.connect(url)的方法直接銜接FTP辦事器
ftpClient.login(username, password);// 登錄
// 設置文件傳輸類型為二進制
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 獲得ftp登錄應對代碼
reply = ftpClient.getReplyCode();
// 驗證能否上岸勝利
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
return result;
}
// 轉移到FTP辦事器目次至指定的目次下
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辦事器上文件下載到當地
*
*/
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();
}
}
這類方法的話須要留意中文亂碼成績啦,假如你設置不適當,有能夠上傳的文件名會為亂碼,有的時刻基本就上傳不上去,固然,也不會跟你提醒,由於本來就沒異常。在網上找了很多多少解答計劃,眾口紛纭,簡直都是從一個版本拷貝曩昔的,也沒有經由本身的真是磨練。為此,也吃了很多甜頭。年夜致分為以下兩種處理計劃:
1、加上以下三句便可處理
ftpClient.setControlEncoding(“GBK”);
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
解答:經由測試,基本下行欠亨,上述成績仍然存在
2、與上述方法有所相似,但我認為這類方法更靠譜一點
起首,加上ftpClient.setControlEncoding(“GBK”);這一句,然後,將一切的中文停止轉碼為“ISO-8859-1”格局,以下:
ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"iso-8859-1"));
解答:經由測試,依然行欠亨,之所以我說此方法更靠譜一點,請持續往下看
起首我們來講說為何要停止轉碼:
由於在FTP協定外面,劃定文件名編碼為iso-8859-1,所以目次名或文件名須要轉碼。
接上去的成績是,我們應當將甚麼編碼轉換為此格局。是以,就有了第二種處理計劃——把 GBK格局的轉換為ISO-8859-1格局。並且,有的人還說,必需得這麼轉。其實,之所以他們能這麼說,我認為完整是偶合。它的真正道理是,既然 FTP協定劃定的編碼格局是“ISO-8859-1”,那末我們確切得將格局轉換一下,然後等辦事器收到文件時再主動轉換為體系自帶的編碼格局,是以,症結不是劃定為何格局,而是取決於FTP辦事器的編碼格局。是以,假如FTP體系的編碼格局為“GBK”時,第二種方法確定會勝利;然則,假如體系的編碼格局為“UTF-8”時,那就會依然湧現亂碼啦。所以,我們只能經由過程代碼先獲得體系的編碼格局,然後經由過程此編碼格局轉換為ISO-8859-1的編碼格局。獲得方法以下:
private static String encoding = System.getProperty("file.encoding");
以上代碼均經由過程本身測試,望能為年夜家處理一下成績!