當前位置:首頁 » 文件管理 » javaftp開發

javaftp開發

發布時間: 2023-05-25 22:47:58

❶ 怎麼用java實現ftp上傳

sun.net.ftp.FtpClient.,該類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP伺服器,列舉該伺服器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變數保存了有關建立"代理"的各種信息。下面給出了這些實例變數:
public static boolean useFtpProxy
這個變數用於表明FTP傳輸過程中是否使用了一個代理,因此,它實際上是一個標記,此標記若為TRUE,表明使用了一個代理主機。
public static String ftpProxyHost
此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機名。
public static int ftpProxyPort此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機的埠地址。
FtpClient有三種不同形式的構造函數,如下所示:
1、public FtpClient(String hostname,int port)
此構造函數利用給出的主機名和埠號建立一條FTP連接。
2、public FtpClient(String hostname)
此構造函數利用給出的主機名建立一條FTP連接,使用默認埠號。
3、FtpClient()
此構造函數將創建一FtpClient類,但不建立FTP連接。這時,FTP連接可以用openServer方法建立。
一旦建立了類FtpClient,就可以用這個類的方法來打開與FTP伺服器的連接。類ftpClient提供了如下兩個可用於打開與FTP伺服器之間的連接的方法。
public void openServer(String hostname)
這個方法用於建立一條與指定主機上的FTP伺服器的連接,使用默認埠號。
public void openServer(String host,int port)
這個方法用於建立一條與指定主機、指定埠上的FTP伺服器的連接。
打開連接之後,接下來的工作是注冊到FTP伺服器。這時需要利用下面的方法。
public void login(String username,String password)
此方法利用參數username和password登錄到FTP伺服器。使用過Intemet的用戶應該知道,匿名FTP伺服器的登錄用戶名為anonymous,密碼一般用自己的電子郵件地址。
下面是FtpClient類所提供的一些控制命令。
public void cd(String remoteDirectory):該命令用於把遠程系統上的目錄切換到參數remoteDirectory所指定的目錄。
public void cdUp():該命令用於把遠程系統上的目錄切換到上一級目錄。
public String pwd():該命令可顯示遠程系統上的目錄狀態。
public void binary():該命令可把傳輸格式設置為二進制格式。
public void ascii():該命令可把傳輸協議設置為ASCII碼格式。
public void rename(String string,String string1):該命令可對遠程系統上的目錄或者文件進行重命名操作。
除了上述方法外,類FtpClient還提供了可用於傳遞並檢索目錄清單和文件的若干方法。這些方法返回的是可供讀或寫的輸入、輸出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回與遠程機器上當前目錄相對應的輸入流。
public TelnetInputStream get(String filename)
獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
public TelnetOutputStream put(String filename)
以寫方式打開一輸出流,通過這一輸出流把文件filename傳送到遠程計算機

package myUtil;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* ftp上傳,下載

*
* @author why 2009-07-30
*
*/
public class FtpUtil {
private String ip = "";
private String username = "";
private String password = "";
private int port = -1;
private String path = "";
FtpClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
public FtpUtil(String serverIP, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
public FtpUtil(String serverIP, int port, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
/**
* 連接ftp伺服器
*
* @throws IOException
*/
public boolean connectServer() {
ftpClient = new FtpClient();
try {
if (this.port != -1) {
ftpClient.openServer(this.ip, this.port);
} else {
ftpClient.openServer(this.ip);
}
ftpClient.login(this.username, this.password);
if (this.path.length() != 0) {
ftpClient.cd(this.path);// path是ftp服務下主目錄的子目錄
}
ftpClient.binary();// 用2進制上傳、下載
System.out.println("已登錄到\"" + ftpClient.pwd() + "\"目錄");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 斷開與ftp伺服器連接
*
* @throws IOException
*/
public boolean closeServer() {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
System.out.println("已從伺服器斷開");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 檢查文件夾在當前目錄下是否存在
*
* @param dir
*@return
*/
private boolean isDirExist(String dir) {
String pwd = "";
try {
pwd = ftpClient.pwd();
ftpClient.cd(dir);
ftpClient.cd(pwd);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 在當前目錄下創建文件夾
*
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir) {
try {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); // sign
s.countTokens();
String pathName = ftpClient.pwd();
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
/**
* ftp上傳 如果伺服器段已存在名為filename的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
*
* @param filename
* 要上傳的文件(或文件夾)名
* @return
* @throws Exception
*/
public boolean upload(String filename) {
String newname = "";
if (filename.indexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1);
} else {
newname = filename;
}
return upload(filename, newname);
}
/**
* ftp上傳 如果伺服器段已存在名為newName的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
*
* @param fileName
* 要上傳的文件(或文件夾)名
* @param newName
* 伺服器段要生成的文件(或文件夾)名
* @return
*/
public boolean upload(String fileName, String newName) {
try {
String savefilename = new String(fileName.getBytes("GBK"),
"GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
upload(file_in.getPath(), newName, ftpClient.pwd());
} else {
uploadFile(file_in.getPath(), newName);
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 真正用於上傳的方法
*
* @param fileName
* @param newName
* @param path
* @throws Exception
*/
private void upload(String fileName, String newName, String path)
throws Exception {
String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
if (!isDirExist(newName)) {
createDir(newName);
}
ftpClient.cd(newName);
File sourceFile[] = file_in.listFiles();
for (int i = 0; i < sourceFile.length; i++) {
if (!sourceFile[i].exists()) {
continue;
}
if (sourceFile[i].isDirectory()) {
this.upload(sourceFile[i].getPath(), sourceFile[i]
.getName(), path + "/" + newName);
} else {
this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
.getName());
}
}
} else {
uploadFile(file_in.getPath(), newName);
}
ftpClient.cd(path);
}
/**
* upload 上傳文件
*
* @param filename
* 要上傳的文件名
* @param newname
* 上傳後的新文件名
* @return -1 文件不存在 >=0 成功上傳,返迴文件的大小
* @throws Exception
*/
public long uploadFile(String filename, String newname) throws Exception {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 從ftp下載文件到本地
*
* @param filename
* 伺服器上的文件名
* @param newfilename
* 本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相對於當前連接目錄的某個目錄下所有文件列表
*
* @param path
* @return
*/
public List getFileList(String path) {
List list = new ArrayList();
DataInputStream dis;
try {
dis = new DataInputStream(ftpClient.nameList(this.path + path));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上傳成功!" : "上傳失敗!");
ftp.closeServer();
/**
* FTP遠程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR
* REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU
* AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR
* NLST MKD XPWD MDTM PROT
* 在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n
* ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令
* ftpclient.readServerResponse一定要在sendServer後調用
* nameList("/test")獲取指目錄下的文件列表 XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯 XRMD刪除目錄
* DELE刪除文件
*/
}
}

❷ 如何用Java實現FTP伺服器

FTP(File Transfer Protocol 文件傳輸協議)是Internet 上用來傳送文件的協議。在Internet上通過FTP 伺服器可以進行文件的上傳(Upload)或下載(Download)。FTP是實時聯機服務,在使用它之前必須是具有該服務的一個用戶(用戶名和口令),工作時客戶端必須先登錄到作為伺服器一方的計算機上,用戶登錄後可以進行文件搜索和文件傳送等有關操作,如改變當前工作目錄、列文件目錄、設置傳輸參數及傳送文件等。使用FTP可以傳送所有類型的文件,如文本文件、二進制可執行文件、圖象文件、聲音文件和數據壓縮文件等。
FTP 命令
FTP 的主要操作都是基於各種命令基礎之上的。常用的命令有:
設置傳輸模式,它包括ASCⅡ(文本) 和BINARY 二進制模式;
目錄操作,改變或顯示遠程計算機的當前目錄(cd、dir/ls 命令);
連接操作,open命令用於建立同遠程計算機的連接;close命令用於關閉連接;
發送操作,put命令用於傳送文件到遠程計算機;mput 命令用於傳送多個文件到遠程計算機;
獲取操作,get命令用於接收一個文件;mget命令用於接收多個文件。
?


import java.net.Socket;import org.apache.log4j.Logger;/** * 角色——伺服器A * @author Leon * */public class ServerA{ public static void main(String[] args){ final String F_DIR = "c:/test";//根路徑 final int PORT = 22;//監聽埠號 Logger.getRootLogger(); Logger logger = Logger.getLogger("com"); try{ ServerSocket s = new ServerSocket(PORT); logger.info("Connecting to server A..."); logger.info("Connected Successful! Local Port:"+s.getLocalPort()+". Default Directory:'"+F_DIR+"'."); while( true ){ //接受客戶端請求 Socket client = s.accept(); //創建服務線程 new ClientThread(client, F_DIR).start(); } } catch(Exception e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } }}import java.io.BufferedReader; import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.io.RandomAccessFile;import java.net.ConnectException;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import java.nio.charset.Charset;import java.util.Random;import org.apache.log4j.Logger;/** * 客戶端子線程類 * @author Leon * */public class ClientThread extends Thread { private Socket socketClient;//客戶端socket private Logger logger;//日誌對象 private String dir;//絕對路徑 private String pdir = "/";//相對路徑 private final static Random generator = new Random();//隨機數 public ClientThread(Socket client, String F_DIR){ this.socketClient = client; this.dir = F_DIR; } @Override public void run() { Logger.getRootLogger(); logger = Logger.getLogger("com"); InputStream is = null; OutputStream os = null; try { is = socketClient.getInputStream(); os = socketClient.getOutputStream(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); PrintWriter pw = new PrintWriter(os); String clientIp = socketClient.getInetAddress().toString().substring(1);//記錄客戶端IP String username = "not logged in";//用戶名 String password = "";//口令 String command = "";//命令 boolean loginStuts = false;//登錄狀態 final String LOGIN_WARNING = "530 Please log in with USER and PASS first."; String str = "";//命令內容字元串 int port_high = 0; int port_low = 0; String retr_ip = "";//接收文件的IP地址 Socket tempsocket = null; //列印歡迎信息 pw.println("220-FTP Server A version 1.0 written by Leon Guo"); pw.flush(); logger.info("("+username+") ("+clientIp+")> Connected, sending welcome message..."); logger.info("("+username+") ("+clientIp+")> 220-FTP Server A version 1.0 written by Leon Guo"); boolean b = true; while ( b ){ try { //獲取用戶輸入的命令 command = br.readLine(); if(null == command) break; } catch (IOException e) { pw.println("331 Failed to get command"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 331 Failed to get command"); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } b = false; } /* * 訪問控制命令 */ // USER命令 if(command.toUpperCase().startsWith("USER")){ logger.info("(not logged in) ("+clientIp+")> "+command); username = command.substring(4).trim(); if("".equals(username)){ pw.println("501 Syntax error"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 501 Syntax error"); username = "not logged in"; } else{ pw.println("331 Password required for " + username); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 331 Password required for " + username); } loginStuts = false; } //end USER // PASS命令 else if(command.toUpperCase().startsWith("PASS")){ logger.info("(not logged in) ("+clientIp+")> "+command); password = command.substring(4).trim(); if(username.equals("root") && password.equals("root")){ pw.println("230 Logged on"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 230 Logged on");// logger.info("客戶端 "+clientIp+" 通過 "+username+"用戶登錄"); loginStuts = true; } else{ pw.println("530 Login or password incorrect!"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 530 Login or password incorrect!"); username = "not logged in"; } } //end PASS // PWD命令 else if(command.toUpperCase().startsWith("PWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){// logger.info("用戶"+clientIp+":"+username+"執行PWD命令"); pw.println("257 /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 257 /""+pdir+"/" is current directory"); } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end PWD // CWD命令 else if(command.toUpperCase().startsWith("CWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ str = command.substring(3).trim(); if("".equals(str)){ pw.println("250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); } else{ //判斷目錄是否存在 String tmpDir = dir + "/" + str; File file = new File(tmpDir); if(file.exists()){//目錄存在 dir = dir + "/" + str; if("/".equals(pdir)){ pdir = pdir + str; } else{ pdir = pdir + "/" + str; }// logger.info("用戶"+clientIp+":"+username+"執行CWD命令"); pw.println("250 CWD successful. /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 CWD successful. /""+pdir+"/" is current directory"); } else{//目錄不存在 pw.println("550 CWD failed. /""+pdir+"/": directory not found."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 550 CWD failed. /""+pdir+"/": directory not found.");

❸ 怎樣用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();
}
}

}

❹ java開發ftp客戶端對伺服器文件狀態如何識別

我們當時是這樣處理的:

上傳一個文件,比如名字為:aaa.rar
當文件上傳完的時候就會上傳一個aaa.fin的空文件做標識,表明這個文件上傳成功。

下載的時候首先檢查aaa.fin是否存在。然後下載!

建議你在文件目錄下放一個list.xml(存放當前上傳成功的文件名,下載前在裡面檢索它是否存在)

❺ 求用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伺服器

FTP是Internet 上用來傳送文件的協議 在Internet上通過FTP 伺服器可以進行文件的上傳(Upload)或下載(Download) FTP是實時聯機服務 在使用它之前必須是具有該服務的一個用戶(用戶名和口令) 工作時客戶端必須先登錄到作為伺服器一方的計算機上 用戶登錄後可以進行文件搜索和文件傳送等有關操作 如改變當前工作目錄 列文件目錄 設置傳輸參數及傳送文件等 使用FTP可以傳送所有類型的文件 如文本文件 二進制可執行文件 圖象文件 聲音文件和數據壓縮文件等 FTP 命令 FTP 的主要操作都是基於各種命令基礎之上的 常用的命令有 ◆ 設置傳輸模式 它包括ASCⅡ(文本) 和BINARY 二進制模式 ◆ 目錄操作 改變或顯示遠程計算機的當前目錄(cd dir/ls 命令) ◆ 連接操作 open命令用於建立同遠程計算機的連接 close命令用於關閉連接 ◆ 發送操作 put命令用於傳送文件到遠程計算機 mput 命令用於傳送多個文件到遠程計算機 ◆ 獲取操作 get命令用於接收一個文件 mget命令用於接收多個文件 編程思路 根據FTP的工作原理 在主函數中建立一個伺服器套接字埠 等待客戶端請求 一旦客戶端請求被接受 伺服器程序就建立一個伺服器分線程 處理客戶端的命令 如果客戶端需要和伺服器端進行文件的傳輸 則建立一個新的套接字連接來完成文件的操作

編程技巧說明 主函數設計 在主函數中 完成伺服器埠的偵聽和服務線程的創建 我們利用一個靜態字元串變數initDir 來保存伺服器線程運行時所在的工作目錄 伺服器的初始工作目錄是由程序運行時用戶輸入的 預設為C盤的根目錄 具體的代碼如下 public class ftpServer extends Thread{ private Socket socketClient; private int counter; private static String initDir; public static void main(String[] args){ if(args length != ) { initDir = args[ ]; }else{ initDir = c: ;} int i = ; try{ System out println( ftp server started! ) //監聽 號埠 ServerSocket s = new ServerSocket( ) for( ){ //接受客戶端請求 Socket ining = s accept() //創建服務線程 new ftpServer(ining i) start() i++; } }catch(Exception e){} } 線程類的設計 線程類的主要設計都是在run()方法中實現 用run()方法得到客戶端的套接字信息 根據套接字得到輸入流和輸出流 向客戶端發送歡迎信息 FTP命令的處理 ( ) 訪問控制命令 ◆ user name(user) 和 password (pass) 命令處理代碼如下 if(str startsWith( USER )){ user = str substring( ) user = user trim() out println( Password ) } if(str startsWith( PASS )) out println( User +user+ logged in ) User 命令和 Password 命令分別用來提交客戶端用戶輸入的用戶名和口令 ◆ CWD (CHANGE WORKING DIRECTORY) 命令處理代碼如下 if(str startsWith( CWD )){ String str = str substring( ) dir = dir+ / +str trim() out println( CWD mand succesful ) } 該命令改變工作目錄到用戶指定的目錄 ◆ CDUP (CHANGE TO PARENT DIRECTORY) 命令處理代碼如下 if(str startsWith( CDUP )){ int n = dir lastIndexOf( / ) dir = dir substring( n) out println( CWD mand succesful ) } 該命令改變當前目錄為上一層目錄 ◆ QUIT命令處理代碼如下 if(str startsWith( QUIT )) { out println( GOOD BYE ) done = true;} 該命令退出及關閉與伺服器的連接 輸出GOOD BYE

( ) 傳輸參數命令 ◆ Port命令處理代碼如下 if(str startsWith( PORT )) { out println( PORT mand successful ) int i = str length() ; int j = str lastIndexOf( ) int k = str lastIndexOf( j ) String str str ;str = ; str = ;for(int l=k+ ; lstr = str + str charAt(l) } for(int l=j+ ;l<=i;l++){ str = str + str charAt(l) } tempPort = Integer parseInt(str ) * * +Integer parseInt(str ) } 使用該命令時 客戶端必須發送客戶端用於接收數據的 位IP 地址和 位 的TCP 埠號 這些信息以 位為一組 使用十進制傳輸 中間用逗號隔開 ◆ TYPE命令處理代碼如下 if(str startsWith( TYPE )){ out println( type set ) } TYPE 命令用來完成類型設置 ( ) FTP 服務命令 ◆ RETR (RETEIEVE) 和 STORE (STORE)命令處理的代碼 if(str startsWith( RETR )){ out println( Binary data connection ) str = str substring( ) str = str trim() RandomAccessFile outFile = newRandomAccessFile(dir+ / +str r ) Socket tempSocket = new Socket(host tempPort) OutputStream outSocket= tempSocket getOutputStream() byte byteBuffer[]= new byte[ ]; int amount; try{ while((amount = outFile read(byteBuffer)) != ){

outSocket write(byteBuffer amount) } outSocket close() out println( transfer plete ) outFile close() tempSocket close() } catch(IOException e){} } if(str startsWith( STOR )){ out println( Binary data connection ) str = str substring( ) str = str trim() RandomAccessFile inFile = newRandomAccessFile(dir+ / +str rw ) Socket tempSocket = new Socket(host tempPort) InputStream inSocket= tempSocket getInputStream() byte byteBuffer[] = new byte[ ]; int amount; try{ while((amount =inSocket read(byteBuffer) )!= ){ inFile write(byteBuffer amount) } inSocket close() out println( transfer plete ) inFile close() tempSocket close() } catch(IOException e) {} } 文件傳輸命令包括從伺服器中獲得文件RETR和向伺服器中發送文件STOR 這兩個命令的處理非常類似 處理RETR命令時 首先得到用戶要獲得的文件的名稱 根據名稱創建一個文件輸入流 然後和客戶端建立臨時套接字連接 並得到一個輸出流 隨後 將文件輸入流中的數據讀出並藉助於套接字輸出流發送到客戶端 傳輸完畢以後 關閉流和臨時套接字 STOR 命令的處理也是同樣的過程 只是方向正好相反 ◆ DELE (DELETE)命令處理代碼如下 if(str startsWith( DELE )){ str = str substring( ) str = str trim() File file = new File(dir str) boolean del = file delete() out println( delete mand successful ) } DELE 命令用於刪除伺服器上的指定文件 ◆ LIST命令處理代碼如下 if(str startsWith( LIST )) { try{ out println( ASCII data ) Socket tempSocket = new Socket(host tempPort) PrintWriter out = new PrintWriter(tempSocket getOutputStream() true) File file = new File(dir) String[] dirStructure = new String[ ]; dirStructure= file list() String strType= ; for(int i= ;iif( dirStructure[i] indexOf( ) == ) { strType = d ;} else{ strType = ;} out println(strType+dirStructure[i]) } tempSocket close() out println( transfer plete ) } catch(IOException e) {} LIST 命令用於向客戶端返回伺服器中工作目錄下的目錄結構 包括文件和目錄的列表 處理這個命令時 先創建一個臨時的套接字向客戶端發送目錄信息 這個套接字的目的埠號預設為 然後為當前工作目錄創建File 對象 利用該對象的list()方法得到一個包含該目錄下所有文件和子目錄名稱的字元串數組 然後根據名稱中是否含有文件名中特有的 來區別目錄和文件 最後 將得到的名稱數組通過臨時套接字發送到客戶端 lishixin/Article/program/Java/hx/201311/26847

❼ JAVA 如何實現FTP遠程路徑

package nc.ui.doc.doc_007;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import nc.itf.doc.DocDelegator;
import nc.vo.doc.doc_007.DirVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;

public class FtpTool {

private FTPClient ftp;

private String romateDir = "";

private String userName = "";

private String password = "";

private String host = "";

private String port = "21";

public FtpTool(String url) throws IOException {
//String url="ftp://user:password@ip:port/ftptest/psd";
int len = url.indexOf("//");
String strTemp = url.substring(len + 2);
len = strTemp.indexOf(":");
userName = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);

len = strTemp.indexOf("@");
password = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
host = "";
len = strTemp.indexOf(":");
if (len < 0)//沒有設置埠
{
port = "21";
len = strTemp.indexOf("/");
if (len > -1) {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
strTemp = "";
}
} else {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("/");
if (len > -1) {
port = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
port = "21";
strTemp = "";
}
}
romateDir = strTemp;
ftp = new FTPClient();
ftp.connect(host, FormatStringToInt(port));

}

public FtpTool(String host, int port) throws IOException {
ftp = new FTPClient();
ftp.connect(host, port);
}

public String login(String username, String password) throws IOException {
this.ftp.login(username, password);
return this.ftp.getReplyString();
}

public String login() throws IOException {
this.ftp.login(userName, password);
System.out.println("ftp用戶: " + userName);
System.out.println("ftp密碼: " + password);
if (!romateDir.equals(""))
System.out.println("cd " + romateDir);
ftp.changeWorkingDirectory(romateDir);
return this.ftp.getReplyString();
}

public boolean upload(String pathname, String filename) throws IOException, BusinessException {

int reply;
int j;
String m_sfilename = null;
filename = CheckNullString(filename);
if (filename.equals(""))
return false;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("FTP server refused connection.");
System.exit(1);
}
FileInputStream is = null;
try {
File file_in;
if (pathname.endsWith(File.separator)) {
file_in = new File(pathname + filename);
} else {
file_in = new File(pathname + File.separator + filename);
}
if (file_in.length() == 0) {
System.out.println("上傳文件為空!");
return false;
}
//產生隨機數最大到99
j = (int)(Math.random()*100);
m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名
is = new FileInputStream(file_in);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.storeFile(m_sfilename, is);
ftp.logout();

} finally {
if (is != null) {
is.close();
}
}
System.out.println("上傳文件成功!");
return true;
}

public boolean delete(String filename) throws IOException {

FileInputStream is = null;
boolean retValue = false;
try {
retValue = ftp.deleteFile(filename);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
return retValue;

}

public void close() {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static int FormatStringToInt(String p_String) {
int intRe = 0;
if (p_String != null) {
if (!p_String.trim().equals("")) {
try {
intRe = Integer.parseInt(p_String);
} catch (Exception ex) {

}
}
}
return intRe;
}

public static String CheckNullString(String p_String) {
if (p_String == null)
return "";
else
return p_String;
}

public boolean downfile(String pathname, String filename) {

String outputFileName = null;
boolean retValue = false;
try {
FTPFile files[] = ftp.listFiles();
int reply = ftp.getReplyCode();

////////////////////////////////////////////////
if (!FTPReply.isPositiveCompletion(reply)) {
try {
throw new Exception("Unable to get list of files to dowload.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/////////////////////////////////////////////////////
if (files.length == 0) {
System.out.println("No files are available for download.");
}else {
for (int i=0; i <files.length; i++) {
System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());
outputFileName = pathname + filename + ".pdf";
//return outputFileName;
File f = new File(outputFileName);

//////////////////////////////////////////////////////
retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));

if (!retValue) {
try {
throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

/////////////////////////////////////////////////////////////
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retValue;
}

}

❽ 能否給一個java開發的具有圖形界面的ftp伺服器客戶端源代碼呢

/ **
*創建日期:2008年12月23日

*類名:Ftp.java

*類路徑:組織結構

*更改日誌:

* / 包組織結構;

進口的java.io.File;

進口java.io.FileInputStream中;

進口java.io.FileOutputStream中;

進口的java。 io.IOException;

進口sun.net.TelnetInputStream;

進口sun.net.TelnetOutputStream;

進口sun.net.ftp.FtpClient;

> / **

* @作者南山地獄

* @說明FTP操作

* /

公共類的Ftp {

/ **

* BR />獲取FTP目錄* / 公共無效getftpList(){

字元串伺服器=「IP地址 /輸入FTP伺服器/>弦樂用戶=」「;/ / FTP伺服器的登錄用戶名

字元串密碼=「」;/ /登錄FTP伺服器的用戶名

字元串路徑密碼=「」;/ / FTP路徑上的伺服器

嘗試{
> FtpClient的FTP客戶端=新FtpClient的();/ /創建FtpClient的對象

ftpClient.openServer(伺服器);/ /連接到FTP伺服器

ftpClient.login(用戶名,密碼);/ / FTP伺服器 BR />如果(path.length()= 0){

ftpClient.cd(路徑);

}

TelnetInputStream是= ftpClient.list();

詮釋三;

而{

System.out.print((char)的C)((C = is.read())= -1!);

}

掉} is.close ();

ftpClient.closeServer();/ /退出FTP伺服器

}趕上(IOException異常前){

System.out.println(ex.getMessage());

}

}

/ **

*
* /

公共無效getFtpFile(){

字元串伺服器=「」;/ / IP地址中輸入FTP伺服器

弦樂用戶=「」;/ / FTP伺服器的登錄用戶名

字元串密碼=「」;/ /登錄密碼為FTP伺服器的用戶名

字元串路徑=「路徑

字元串文件名「;/ /上=的FTP伺服器」「;/ /下載文件名稱

嘗試{

FtpClient的FTP客戶端=新FtpClient的();

ftpClient.openServer(伺服器);

ftpClient.login(用戶名,密碼);

如果(路徑。長度()= 0)

ftpClient.cd(路徑);!

ftpClient.binary();

TelnetInputStream是= ftpClient.get(文件名);

文件file_out =新的文件(文件名);

文件輸出流OS =新的文件輸出流(file_out);

位元組[]位元組=新位元組[1024];

詮釋三;

而((C = is.read(位元組))= -1){

os.write (位元組,0,C);

}!

掉} is.close();

os.close();

ftpClient.closeServer();

}趕上(IOException異常前){

System.out.println (ex.getMessage());

}

FTP}

/ **

*文件上傳到FTP

* /

公共無效putFtpFile() {

字元串伺服器=「」;/ /輸入IP地址對伺服器

字元串用戶的地址=「」;/ / FTP伺服器的登錄用戶名

字元串密碼=「」;/ / FTP伺服器登錄用戶名密碼

字元串路徑=「」就 / FTP伺服器/>字元串文件名=「」;/ /上傳的文件名

FtpClient的FTP客戶端=新的try { FtpClient的();

ftpClient.openServer(伺服器);

ftpClient.login(用戶名,密碼);

如果(!path.length()= 0)

ftpClient.cd (路徑);

ftpClient.binary();

TelnetOutputStream OS = ftpClient.put(文件名);

文件file_in =新的文件(文件名);

文件輸入流是=新的文件輸入流(file_in);

位元組[]位元組=新位元組[1024];

詮釋三;

同時(! (C = is.read(位元組))= -1){

操作系統。寫(位元組,0,C);

}

掉} is.close();

os.close();

ftpClient.closeServer();

}趕上(IOException異常前){

System.out.println(ex.getMessage());

}

}
}

熱點內容
網路編程畢設 發布:2024-04-26 14:13:10 瀏覽:207
秦九韶演算法教案 發布:2024-04-26 13:30:22 瀏覽:412
解壓到當前文件夾右鍵 發布:2024-04-26 03:57:08 瀏覽:979
html5android教程視頻下載 發布:2024-04-26 03:09:59 瀏覽:867
伺服器的描述是什麼 發布:2024-04-26 03:08:32 瀏覽:394
個人加密 發布:2024-04-26 03:01:23 瀏覽:521
linuxusbgadget 發布:2024-04-26 02:52:54 瀏覽:304
我的世界空島世界伺服器地址 發布:2024-04-26 01:39:08 瀏覽:248
尼爾機械紀元加密 發布:2024-04-26 01:37:11 瀏覽:868
在控制台輸出sql語句 發布:2024-04-26 01:08:12 瀏覽:432