javaftp客戶端
java ftp 最常用的是apache commons-net
commons-net項目中封裝了各種網路協議的客戶端,支持的協議包括:
FTP
NNTP
SMTP
POP3
Telnet
TFTP
Finger
Whois
rexec/rcmd/rlogin
Time (rdate) and Daytime
Echo
Discard
NTP/SNTP
其他的還有FTP4J ,jftp
⑵ java ftp
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import sun.net.ftp.FtpClient;
/**
*
* @author chenc
* @version 1.0
*
* 2008-02-19
*
*/
public class Ftp {
private String ip = "";
private String username = "";
private String password = "";
private String ftpDir = "";
private String localFileFullName = "";// 待上傳的文件全名
private String ftpFileName = ""; // 文件上傳到FTP後的名稱
FtpClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
public Ftp(String serverIP, String username, String password, String ftpDir) {
this.ip = serverIP;
this.username = username;
this.password = password;
if (ftpDir == null) {
this.ftpDir = "/ftpfileload";
} else {
try {
this.ftpDir = "/"
+ new String(ftpDir.getBytes("ISO-8859-1"), "GBK")
.toString();
} catch (UnsupportedEncodingException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
}
private void createDir(String dir, FtpClient ftpClient) {
System.out.println(this.ftpDir);
ftpClient.sendServer("MKD " + dir + "\r\n");
try {
ftpClient.readServerResponse();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
private Boolean isDirExist(String dir, FtpClient ftpClient) {
try {
ftpClient.cd(dir);
} catch (Exception e) {
// TODO 自動生成 catch 塊
return false;
}
return true;
}
public String upload(String localFileFullName) {
// this.ftpFileName = "aaa.test";
// 獲取文件後綴名
String ext = localFileFullName.substring(localFileFullName
.lastIndexOf("."));
// System.out.println(ext);
// 產生新文件名,用系統當前時間+文件原有後綴名
long newFileName = System.currentTimeMillis();
String newFileFullName = newFileName + ext;
// System.out.println("new file name:"+newFileFullName);
this.ftpFileName = newFileFullName;
try {
String savefilename = new String(localFileFullName
.getBytes("ISO-8859-1"), "GBK");
// 新建一個FTP客戶端連接
ftpClient = new FtpClient();
ftpClient.openServer(this.ip);
ftpClient.login(this.username, this.password);
// 判斷並創建目錄
if (!isDirExist(this.ftpDir, ftpClient)) {
createDir(this.ftpDir, ftpClient);
}
ftpClient.cd(this.ftpDir);// 切換到FTP目錄
ftpClient.binary();
os = ftpClient.put(this.ftpFileName);
// 打開本地待長傳的文件
File file_in = new File(savefilename);
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
// 開始復制
int c;
// 暫未考慮中途終止的情況
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
} catch (Exception e) {
System.err.println("Exception e in Ftp upload() finally"
+ e.toString());
}
}
return this.ftpFileName;
}
public void delFile(String dir, String filename) {
ftpClient = new FtpClient();
try {
ftpClient.openServer(this.ip);
ftpClient.login(this.username, this.password);
if (dir.length() > 0) {
ftpClient.cd(dir);
}
ftpClient.sendServer("DELE " + filename + "\r\n");
ftpClient.readServerResponse();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
}
我寫的一個FTP類,你看看你能不能用。。。。。
⑶ 求用java寫一個ftp伺服器客戶端程序。
import java.io.*;
import java.net.*;public class ftpServer extends Thread{ public static void main(String args[]){
String initDir;
initDir = "D:/Ftp";
ServerSocket server;
Socket socket;
String s;
String user;
String password;
user = "root";
password = "123456";
try{
System.out.println("MYFTP伺服器啟動....");
System.out.println("正在等待連接....");
//監聽21號埠
server = new ServerSocket(21);
socket = server.accept();
System.out.println("連接成功");
System.out.println("**********************************");
System.out.println("");
InputStream in =socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream din = new DataInputStream(in);
DataOutputStream dout=new DataOutputStream(out);
System.out.println("請等待驗證客戶信息....");
while(true){
s = din.readUTF();
if(s.trim().equals("LOGIN "+user)){
s = "請輸入密碼:";
dout.writeUTF(s);
s = din.readUTF();
if(s.trim().equals(password)){
s = "連接成功。";
dout.writeUTF(s);
break;
}
else{s ="密碼錯誤,請重新輸入用戶名:";<br> dout.writeUTF(s);<br> <br> }
}
else{
s = "您輸入的命令不正確或此用戶不存在,請重新輸入:";
dout.writeUTF(s);
}
}
System.out.println("驗證客戶信息完畢...."); while(true){
System.out.println("");
System.out.println("");
s = din.readUTF();
if(s.trim().equals("DIR")){
String output = "";
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
for(int i=0;i<dirStructure.length;i++){
output +=dirStructure[i]+"\n";
}
s=output;
dout.writeUTF(s);
}
else if(s.startsWith("GET")){
s = s.substring(3);
s = s.trim();
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
String e= s;
int i=0;
s ="不存在";
while(true){
if(e.equals(dirStructure[i])){
s="存在";
dout.writeUTF(s);
RandomAccessFile outFile = new RandomAccessFile(initDir+"/"+e,"r");
byte byteBuffer[]= new byte[1024];
int amount;
while((amount = outFile.read(byteBuffer)) != -1){
dout.write(byteBuffer, 0, amount);break;
}break;
}
else if(i<dirStructure.length-1){
i++;
}
else{
dout.writeUTF(s);
break;
}
}
}
else if(s.startsWith("PUT")){
s = s.substring(3);
s = s.trim();
RandomAccessFile inFile = new RandomAccessFile(initDir+"/"+s,"rw");
byte byteBuffer[] = new byte[1024];
int amount;
while((amount =din.read(byteBuffer) )!= -1){
inFile.write(byteBuffer, 0, amount);break;
}
}
else if(s.trim().equals("BYE"))break;
else{
s = "您輸入的命令不正確或此用戶不存在,請重新輸入:";
dout.writeUTF(s);
}
}
din.close();
dout.close();
in.close();
out.close();
socket.close();
}
catch(Exception e){
System.out.println("MYFTP關閉!"+e);
}
}}
⑷ 關於JAVA FTP 客戶端程序異常
501 PORT not allowed after EPSV ALL~~~說明還是網路的問題,我對網路不熟~~~比如用ftp工具的時候,有些ftp站點必須採用被動模式才能連接。下面的你看看吧,或許有用,找網管看看應該使用哪種方式訪問
***************************************************
3. EPSV命令
EPSV請求伺服器在一個數據埠上偵聽等待連接,它可以帶參數。對它的響應是TCP埠號。響應的格式與EPRT參數的很象。這對實現上有很大的方便。而且響應還留下了網路協議和/或網路地址的空位,可以供以後使用。使用擴展地址進行被動模式的響應碼必須是229,對它的解釋如下:
2yz 主動完成
x2z 連接
xy9 進行擴展的被動模式
響應的格式如下:
<指示伺服器已經進入初擴展的被動模式>
(<d><d><d><TCP埠><d>)
包括在括弧內的字元串必須是EPRT打開數據連接的埠。具體如上所未,這里就不多說了。數據連接使用的協議必須和控制連接使用的協議和地址一致,下面是響應的一個例子:
Entering Extended Passive Mode (|||6446|)
標准錯誤代碼500和501對EPSV已經足夠了。在EPSV命令沒有使用參數時,伺服器會基於控制連接所使用的協議選擇數據連接使用的網路協議。但是在有代理的情況下,這種機制可能不合適。因此客戶也需要能夠要求一個指定協議。如果伺服器返回說明它在指定埠不支持此協議,客戶必須發送ABOR(放棄)命令使伺服器關閉連接,然後客戶再使用EPSV命令要求使用特定的網路協議,具體格式如下:
EPSV<空格><網路協議>
如果請求的網路協議是伺服器支持的,那就必須使用此協議;如果不支持,則返回522。最後,EPSV命令可以使用參數"ALL"通過網路地址翻譯器,EPRT命令不再使用。下面是例子:
EPSV<空格>ALL
接收到此命令後,伺服器要拒絕除了EPSV以外所有建立連接的命令。在下一節我們將詳細說明此命令的功能。
**********************************************************************
⑸ 用java實現sftp的客戶端,channel.connect()的時候,拋出異常,收到信息過長,然後就沒連上。怎麼回事
首先,不太明確你要問什麼?
J2EE是java企業級應用,它裡面關於安全方面的東西很多!
許可權管理?信息安全?授權服務?訪問控制?數據機密性?
要是你想全部都了解!
在這里提問是不行的!太龐雜了!
如果 你要問的是 java ftp傳輸過程中的一些安全注意事項!
這里建議 你使用 apache的開源項目。他們把基於java的ftp操作都封裝好了!
安全相關都有保證。
我下面可以給你復制一段 ftp下載遠程終端的java代碼!你可以參考一下!
需要下載 org.apache.commons.net包
可以到 網站下載!
/**
* Description: 從FTP伺服器下載文件
* @param ip FTP伺服器的ip地址
* @param port FTP伺服器埠,默認為:21
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param remotePath FTP伺服器上的相對路徑
* @param fileName 要下載的文件名
* @param localPath 下載後保存到本地的路徑
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath,String fileName,String localPath,String localfile) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//處理中文轉碼操作
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//轉移到FTP伺服器目錄
FTPFile[] fs = ftp.listFiles();
for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){
String localfilename = localfile;//按規則設置文件名這里你要下載文件,可以自己定義下載之後的文件名
File localFile = new File(localPath+File.separator+localfilename);
OutputStream is = new FileOutputStream(localFile);
//此處retrieveFile的第一個參數由GBK轉為ISO-8859-1編碼。否則下載後的文件內容為空。
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);
is.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
⑹ Java 編寫FTP客戶端登錄的問題。
try {
FtpClient ftp = new FtpClient("192.168.1.101");
ftp.login("Administrator", "123");
System.out.println("-------");
} catch (IOException e) {
System.out.println("************");
e.printStackTrace();
}
我這個也是用的sun的FTPClient
我測試的時候好使啊!
你的ftp配置是不是有問題啊!
lz再好好看看吧!
你也可以試試Apache的FTPClient
⑺ java ftp 和 sftp的區別
文件傳送協議FTP(File Transfer Protocol)是TCP/IP協議簇中的一個成員,也是現在網際網路上最廣泛的文件傳送協議。FTP協議包括兩個部分,一個是FTP客戶端,另一個是FTP伺服器。當然,FTP伺服器是用來存儲文件資源的,FTP客戶端通過訪問FTP伺服器來獲得資源的。
安全文件傳送協議SFTP(Secure File Transfer Protocol)可以為文件傳送提供安全的加密/解密技術。基本語法和FTP差不多。SFTP是SSH的一部分,在SSH軟體包中,已經包含了一個SFTP(Secure File Transfer Protocol)的安全文件傳輸子系統,SFTP本身沒有單獨的守護進程,它必須使用sshd守護進程(埠號默認是22)來完成相應的連接操作。由於這種傳輸方式使用了加密/解密技術,文件傳送相對來說是很安全的,但是是有代價的,它的傳輸效率比FTP要低得多。
引自:網頁鏈接
⑻ java中怎麼實現ftp伺服器
我知道apache有個commons net包,其中的FTPClient類可以實現客戶端和服務之間的文件傳輸,但是我如果使用這種方式的話,就得將一台伺服器上的文件傳到我本地,再將這個文件傳到另一台伺服器上,感覺這中間多了一步操作;
⑼ java開發ftp客戶端對伺服器文件狀態如何識別
我們當時是這樣處理的:
上傳一個文件,比如名字為:aaa.rar
當文件上傳完的時候就會上傳一個aaa.fin的空文件做標識,表明這個文件上傳成功。
下載的時候首先檢查aaa.fin是否存在。然後下載!
建議你在文件目錄下放一個list.xml(存放當前上傳成功的文件名,下載前在裡面檢索它是否存在)
⑽ 怎樣用java開發ftp客戶端
package zn.ccfccb.util;
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import zn.ccfccb.util.CCFCCBUtil;
import zn.ccfccb.util.ZipUtilAll;
public class CCFCCBFTP {
/**
* 上傳文件
*
* @param fileName
* @param plainFilePath 明文文件路徑路徑
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上傳文件開始");
Log.info("連接遠程上傳伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// Log.info("連接遠程上傳伺服器"+"192.168.54.106:"+2021);
// ftpClient.connect("192.168.54.106", 2021);
// ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz");
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("檢查文件路徑是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查詢文件路徑不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上傳文件成功:"+fileName+"。文件保存路徑:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
/**
*下載並解壓文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下載並解密文件開始");
Log.info("連接遠程下載伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;
ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下載文件開始。");
ftpClient.setBufferSize(1024);
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下載文件結束:"+localFilePath);
}
}
Log.info("檢查文件是否存:"+fileName+" "+bl);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查詢無結果,請稍後再查詢。");
return bl;
}
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
// 調用樣例:
public static void main(String[] args) {
try {
// 密鑰/res/20150228
// ZipUtilAll.unZip(new File(("D:/123/123.zip")), "D:/123/");
// ZipDemo1232.unZip(new File(("D:/123/123.zip")), "D:/123/");
// 明文文件路徑
String plainFilePath = "D:/req_20150204_0011.txt";
// 密文文件路徑
String secretFilePath = "req_20150204_00134.txt";
// 加密
// encodeAESFile(key, plainFilePath, secretFilePath);
fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
ZipUtilAll.unZip("D://123.zip", "D:/123/李筱/");
// 解密
plainFilePath = "D:/123.sql";
// secretFilePath = "D:/test11111.sql";
// decodeAESFile(key, plainFilePath, secretFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
