A. java 實現ftp上傳下載,windows下和linux下游何區別
packagecom.weixin.util;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.RandomAccessFile;
importorg.apache.commons.net.PrintCommandListener;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcom.weixin.constant.DownloadStatus;
importcom.weixin.constant.UploadStatus;
/**
*支持斷點續傳的FTP實用類
*@version0.1實現基本斷點上傳下載
*@version0.2實現上傳下載進度匯報
*@version0.3實現中文目錄創建及中文文件創建,添加對於中文的支持
*/
publicclassContinueFTP{
publicFTPClientftpClient=newFTPClient();
publicContinueFTP(){
//設置將過程中使用到的命令輸出到控制台
this.ftpClient.addProtocolCommandListener(newPrintCommandListener(newPrintWriter(System.out)));
}
/**
*連接到FTP伺服器
*@paramhostname主機名
*@paramport埠
*@paramusername用戶名
*@parampassword密碼
*@return是否連接成功
*@throwsIOException
*/
publicbooleanconnect(Stringhostname,intport,Stringusername,Stringpassword)throwsIOException{
ftpClient.connect(hostname,port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username,password)){
returntrue;
}
}
disconnect();
returnfalse;
}
/**
*從FTP伺服器上下載文件,支持斷點續傳,上傳百分比匯報
*@paramremote遠程文件路徑
*@paramlocal本地文件路徑
*@return上傳的狀態
*@throwsIOException
*/
publicDownloadStatusdownload(Stringremote,Stringlocal)throwsIOException{
//設置被動模式
ftpClient.enterLocalPassiveMode();
//設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatusresult;
//檢查遠程文件是否存在
FTPFile[]files=ftpClient.listFiles(newString(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length!=1){
System.out.println("遠程文件不存在");
returnDownloadStatus.Remote_File_Noexist;
}
longlRemoteSize=files[0].getSize();
Filef=newFile(local);
//本地存在文件,進行斷點下載
if(f.exists()){
longlocalSize=f.length();
//判斷本地文件大小是否大於遠程文件大小
if(localSize>=lRemoteSize){
System.out.println("本地文件大於遠程文件,下載中止");
returnDownloadStatus.Local_Bigger_Remote;
}
//進行斷點續傳,並記錄狀態
FileOutputStreamout=newFileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=localSize/step;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下載進度:"+process);
//TODO更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
booleanisDo=ftpClient.completePendingCommand();
if(isDo){
result=DownloadStatus.Download_From_Break_Success;
}else{
result=DownloadStatus.Download_From_Break_Failed;
}
}else{
OutputStreamout=newFileOutputStream(f);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=0;
longlocalSize=0L;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下載進度:"+process);
//TODO更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
booleanupNewStatus=ftpClient.completePendingCommand();
if(upNewStatus){
result=DownloadStatus.Download_New_Success;
}else{
result=DownloadStatus.Download_New_Failed;
}
}
returnresult;
}
/**
*上傳文件到FTP伺服器,支持斷點續傳
*@paramlocal本地文件名稱,絕對路徑
*@paramremote遠程文件路徑,使用/home/directory1/subdirectory/file.ext按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
*@return上傳結果
*@throwsIOException
*/
publicUploadStatusupload(Stringlocal,Stringremote)throwsIOException{
//設置PassiveMode傳輸
ftpClient.enterLocalPassiveMode();
//設置以二進制流的方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatusresult;
//對遠程目錄的處理
StringremoteFileName=remote;
if(remote.contains("/")){
remoteFileName=remote.substring(remote.lastIndexOf("/")+1);
//創建伺服器遠程目錄結構,創建失敗直接返回
if(CreateDirecroty(remote,ftpClient)==UploadStatus.Create_Directory_Fail){
returnUploadStatus.Create_Directory_Fail;
}
}
//檢查遠程是否存在文件
FTPFile[]files=ftpClient.listFiles(newString(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length==1){
longremoteSize=files[0].getSize();
Filef=newFile(local);
longlocalSize=f.length();
if(remoteSize==localSize){
returnUploadStatus.File_Exits;
}elseif(remoteSize>localSize){
returnUploadStatus.Remote_Bigger_Local;
}
//嘗試移動文件內讀取指針,實現斷點續傳
result=uploadFile(remoteFileName,f,ftpClient,remoteSize);
//如果斷點續傳沒有成功,則刪除伺服器上文件,重新上傳
if(result==UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
returnUploadStatus.Delete_Remote_Faild;
}
result=uploadFile(remoteFileName,f,ftpClient,0);
}
}else{
result=uploadFile(remoteFileName,newFile(local),ftpClient,0);
}
returnresult;
}
/**
*斷開與遠程伺服器的連接
*@throwsIOException
*/
publicvoiddisconnect()throwsIOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
/**
*遞歸創建遠程伺服器目錄
*@paramremote遠程伺服器文件絕對路徑
*@paramftpClientFTPClient對象
*@return目錄創建是否成功
*@throwsIOException
*/
(Stringremote,FTPClientftpClient)throwsIOException{
UploadStatusstatus=UploadStatus.Create_Directory_Success;
Stringdirectory=remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(newString(directory.getBytes("GBK"),"iso-8859-1"))){
//如果遠程目錄不存在,則遞歸創建遠程伺服器目錄
intstart=0;
intend=0;
if(directory.startsWith("/")){
start=1;
}else{
start=0;
}
end=directory.indexOf("/",start);
while(true){
StringsubDirectory=newString(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else{
System.out.println("創建目錄失敗");
returnUploadStatus.Create_Directory_Fail;
}
}
start=end+1;
end=directory.indexOf("/",start);
//檢查所有目錄是否創建完畢
if(end<=start){
break;
}
}
}
returnstatus;
}
/**
*上傳文件到伺服器,新上傳和斷點續傳
*@paramremoteFile遠程文件名,在上傳之前已經將伺服器工作目錄做了改變
*@paramlocalFile本地文件File句柄,絕對路徑
*@paramprocessStep需要顯示的處理進度步進值
*@paramftpClientFTPClient引用
*@return
*@throwsIOException
*/
publicUploadStatusuploadFile(StringremoteFile,FilelocalFile,FTPClientftpClient,longremoteSize)throwsIOException{
UploadStatusstatus;
//顯示進度的上傳
longstep=localFile.length()/100;
longprocess=0;
longlocalreadbytes=0L;
RandomAccessFileraf=newRandomAccessFile(localFile,"r");
OutputStreamout=ftpClient.appendFileStream(newString(remoteFile.getBytes("GBK"),"iso-8859-1"));
//斷點續傳
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process=remoteSize/step;
raf.seek(remoteSize);
localreadbytes=remoteSize;
}
byte[]bytes=newbyte[1024];
intc;
while((c=raf.read(bytes))!=-1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes/step!=process){
process=localreadbytes/step;
System.out.println("上傳進度:"+process);
//TODO匯報上傳狀態
}
}
out.flush();
raf.close();
out.close();
booleanresult=ftpClient.completePendingCommand();
if(remoteSize>0){
status=result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else{
status=result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
returnstatus;
}
publicstaticvoidmain(String[]args){
ContinueFTPmyFtp=newContinueFTP();
try{
System.err.println(myFtp.connect("10.10.6.236",21,"5","jieyan"));
// myFtp.ftpClient.makeDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(newString("愛你等於愛自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\yw.flv","/yw.flv",5));
// System.out.println(myFtp.upload("E:\愛你等於愛自己.mp4","/愛你等於愛自己.mp4"));
//System.out.println(myFtp.download("/愛你等於愛自己.mp4","E:\愛你等於愛自己.mp4"));
myFtp.disconnect();
}catch(IOExceptione){
System.out.println("連接FTP出錯:"+e.getMessage());
}
}
}
B. java 實現ftp上傳如何創建文件夾
准備條件:java實現ftp上傳用到了commons-net-3.3.jar包
首先建立ftphost連接
publicbooleanconnect(Stringpath,Stringaddr,intport,Stringusername,Stringpassword){
try{
//FTPClientftp=newFTPHTTPClient(addr,port,username,password);
ftp=newFTPClient();
intreply;
ftp.connect(addr);
System.out.println("連接到:"+addr+":"+port);
System.out.print(ftp.getReplyString());
reply=ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
System.err.println("FTP目標伺服器積極拒絕.");
System.exit(1);
returnfalse;
}else{
ftp.login(username,password);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(path);
System.out.println("已連接:"+addr+":"+port);
returntrue;
}
}catch(Exceptionex){
ex.printStackTrace();
System.out.println(ex.getMessage());
returnfalse;
}
}
然後再利用ftpclient的makeDirectory方法創建文件夾
publicvoidcreateDir(Stringdirname){
try{
ftp.makeDirectory(dirname);
System.out.println("在目標伺服器上成功建立了文件夾:"+dirname);
}catch(Exceptionex){
System.out.println(ex.getMessage());
}
}
斷開host連接
publicvoiddisconnect(){
try{
ftp.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
最後是程序的調用方法
publicstaticvoidmain(String[]args){
FtpUploadTestftpupload=newFtpUploadTest();
if(ftpupload.connect("","172.39.8.x",20,"administrator","abc@123")){
ftpupload.createDir("/UPLOAD");
ftpupload.disconnect();
}
}
C. java ftpclient怎麼傳輸多個文件
/**
* Description: 向FTP伺服器上傳文件
* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建
* @param url FTP伺服器hostname
* @param port FTP伺服器埠
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param path FTP伺服器保存目錄
* @param filename 上傳到FTP伺服器上的文件名
* @param input 輸入流
* @return 成功返回true,否則返回false
*/
publicstaticboolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//連接FTP伺服器
//如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}<pre></pre>
D. java如何實現將FTP文件轉移到另一個FTP伺服器上
你有FTPClient就比較好辦,假如你的兩台FTP伺服器分別為fs1和fs2
在本地開發代碼思路如下:
通過FTPClient連接上fs1,然後下載(可以循環批量下載)到本地伺服器,保存到一個臨時目錄。
下載完成後,FTPClient斷開與fs1的連接,記得必須logout。
本地伺服器通過FileInputStream將剛下載到臨時目錄的文件讀進來,得到一個List<File>集合。
通過FTPClient連接上fs2,循環List<File>集合,將文件上傳至fs2的特定目錄,然後清空臨時目錄,上傳完畢後,斷開fs2的連接,同樣必須logout。
E. 用java有一個ftp路徑地址,需要把傳送一些數據到ftp中怎樣實現
1.使用的FileZillaServer開源,安裝過後建立的本地FTP伺服器。2.使用的apache上FTP工具包,引用到工程目錄中。3.IDE,Eclipse,JDK6上傳和目錄的實現原理:對每一個層級的目錄進行判斷,是為目錄類型、還是文件類型。如果為目錄類型,採用遞歸調用方法,檢查到最底層的目錄為止結束。如果為文件類型,則調用上傳或者方法對文件進行上傳或者操作。貼出代碼:(其中有些沒有代碼,可以看看,還是很有用處的)!
F. java如何實現兩台ftp伺服器之間的文件傳輸10
�0�2我知道apache有個commons net包,其中的FTPClient類可以實現客戶端和服務之間的文件傳輸,但是我如果使用這種方式的話,就得將一台伺服器上的文件傳到我本地,再將這個文件傳到另一台伺服器上,感覺這中間多了一步操作;我想請問大家如何能不通過本機,直接操作兩台伺服器,將文件從一台伺服器傳到另一台伺服器上,如果有人知道實現方式,希望不吝賜教,謝謝了!問題補充:<div class="quote_title"suziwen 寫道</div<div class="quote_div"把JAVA程序放在其中一台FTP服務 器A上,通過A伺服器上的JAVA登錄到另一台FTP伺服器,F代碼執行文 件的上傳,下載。 / /</div / /謝謝你們的回答,你們說的這種方式我明白。
G. java jdk1.6環境下實現 ftp文件上傳
通過JDK自帶的API實現
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();
}
}