當前位置:首頁 » 文件管理 » java原生ftp

java原生ftp

發布時間: 2022-11-20 14:08:11

❶ 如何在java程序中實現ftp上傳下載功能

以下是這三部分的JAVA源程序: (1)顯示FTP伺服器上的文件 void ftpList_actionPerformed(ActionEvent e) {String server=serverEdit.getText();//輸入的FTP伺服器的IP地址 String user=userEdit.getText();//登錄FTP伺服器的用戶名 String password=passwordEdit.getText();//登錄FTP伺服器的用戶名的口令 String path=pathEdit.getText();//FTP伺服器上的路徑 try {FtpClient ftpClient=new FtpClient();//創建FtpClient對象 ftpClient.openServer(server);//連接FTP伺服器 ftpClient.login(user, password);//登錄FTP伺服器 if (path.length()!=0) ftpClient.cd(path); TelnetInputStream is=ftpClient.list(); int c; while ((c=is.read())!=-1) { System.out.print((char) c);} is.close(); ftpClient.closeServer();//退出FTP伺服器 } catch (IOException ex) {;} } (2)從FTP伺服器上下傳一個文件 void getButton_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); String user=userEdit.getText(); String password=passwordEdit.getText(); String path=pathEdit.getText(); String filename=filenameEdit.getText(); try { FtpClient ftpClient=new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); if (path.length()!=0) ftpClient.cd(path); ftpClient.binary(); TelnetInputStream is=ftpClient.get(filename); File file_out=new File(filename); FileOutputStream os=new FileOutputStream(file_out); byte[] bytes=new byte[1024]; int c; while ((c=is.read(bytes))!=-1) { os.write(bytes,0,c); } is.close(); os.close(); ftpClient.closeServer(); } catch (IOException ex) {;} } (3)向FTP伺服器上上傳一個文件 void putButton_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); String user=userEdit.getText(); String password=passwordEdit.getText(); String path=pathEdit.getText(); String filename=filenameEdit.getText(); try { FtpClient ftpClient=new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); if (path.length()!=0) ftpClient.cd(path); ftpClient.binary(); TelnetOutputStream os=ftpClient.put(filename); File file_in=new File(filename); FileInputStream is=new FileInputStream(file_in); byte[] bytes=new byte[1024]; int c; while ((c=is.read(bytes))!=-1){ os.write(bytes,0,c);} is.close(); os.close(); ftpClient.closeServer(); } catch (IOException ex) {;} } }

❷ java 實現ftp上傳如何創建文件夾

這個功能我也剛寫完,不過我也是得益於同行,現在我也把自己的分享給大家,希望能對大家有所幫助,因為自己的項目不涉及到創建文件夾,也僅作分享,不喜勿噴謝謝!

interface:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;

publicinterfaceIFtpUtils{
/**
*ftp登錄
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@paramfpathftp路徑
*@paramlocalpath本地路徑
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下載文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*關閉流連接、ftp連接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}

impl:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;

{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;

@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//設置文件類型為二進制(避免解壓縮文件失敗)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//開通數據埠傳輸數據,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("連接FTP失敗,用戶名或密碼錯誤");
}else{
log.info("FTP連接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登錄FTP失敗,請檢查FTP相關配置信息是否正確",e1);
}
}
}
returnftpClient;
}

@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上傳失敗");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上傳成功");
}
returnfalse;
}

@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切換到當前目錄
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;

}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下載成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}

@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夾是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,請檢查。。。");
}
}
}
}
}


@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}


publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下載/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}

❸ 如何用java連接到ftp上

現在已經封裝好了的方法,不需要任何其他知識即可連接的。只需要知道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;

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);
}

❹ Java的ftp操作方法有哪幾種

FTP(File Transfer Protocol)是 Internet 上用來傳送文件的協議(文件傳輸協議)。它是為了我們能夠在 Internet 上互相傳送文件而制定的的文件傳送標准,規定了 Internet 上文件如何傳送。也就是說,通過 FTP 協議,我們就可以跟 Internet 上的 FTP 伺服器進行文件的上傳(Upload)或下載(Download)等動作。

和其他 Internet 應用一樣,FTP 也是依賴於客戶程序/伺服器關系的概念。在 Internet 上有一些網站,它們依照 FTP 協議提供服務,讓網友們進行文件的存取,這些網站就是 FTP 伺服器。網上的用戶要連上 FTP 伺服器,就要用到 FPT 的客戶端軟體,通常 Windows 都有「ftp」命令,這實際就是一個命令行的 FTP 客戶程序,另外常用的 FTP 客戶程序還有 CuteFTP、Ws_FTP、FTP Explorer等。

要連上 FTP 伺服器(即「登陸」),必須要有該 FTP 伺服器的帳號。如果是該伺服器主機的注冊客戶,你將會有一個 FTP 登陸帳號和密碼,就憑這個帳號密碼連上該伺服器。但 Internet 上有很大一部分 FTP 伺服器被稱為「匿名」(Anonymous)FTP 伺服器。這類伺服器的目的是向公眾提供文件拷貝服務,因此,不要求用戶事先在該伺服器進行登記注冊。

Anonymous(匿名文件傳輸)能夠使用戶與遠程主機建立連接並以匿名身份從遠程主機上拷貝文件,而不必是該遠程主機的注冊用戶。用戶使用特殊的用戶名「anonymous」和「guest」就可有限制地訪問遠程主機上公開的文件。現在許多系統要求用戶將Emai1地址作為口令,以便更好地對訪問進行跟綜。出於安全的目的,大部分匿名FTP主機一般只允許遠程用戶下載(download)文件,而不允許上載(upload)文件。也就是說,用戶只能從匿名FTP主機拷貝需要的文件而不能把文件拷貝到匿名FTP主機。另外,匿名FTP主機還採用了其他一些保護措施以保護自己的文件不至於被用戶修改和刪除,並防止計算機病毒的侵入。在具有圖形用戶界面的 WorldWild Web環境於1995年開始普及以前,匿名FTP一直是Internet上獲取信息資源的最主要方式,在Internet成千上萬的匿名PTP主機中存儲著無以計數的文件,這些文件包含了各種各樣的信息,數據和軟體。 人們只要知道特定信息資源的主機地址, 就可以用匿名FTP登錄獲取所需的信息資料。雖然目前使用WWW環境已取代匿名FTP成為最主要的信息查詢方式,但是匿名FTP仍是 Internet上傳輸分發軟體的一種基本方法

❺ java中怎麼實現ftp伺服器

我知道apache有個commons net包,其中的FTPClient類可以實現客戶端和服務之間的文件傳輸,但是我如果使用這種方式的話,就得將一台伺服器上的文件傳到我本地,再將這個文件傳到另一台伺服器上,感覺這中間多了一步操作;

❻ Java怎麼均衡訪問多台ftp伺服器

多次需要把文件上傳到單獨的伺服器,而程序是在單獨的伺服器上部署的,在進行文件操作的時候就需要跨伺服器進行操作包括:文件上傳、文件下載、文件刪除等。跨伺服器文件操作一般是需要FTP協議和SFTP協議兩種,現在就通過Java實現FTP協議的文件上傳。要實現FTP操作文件需要引入jar包: commons-net-1.4.1.jar

參考資料來源:網路貼吧

❼ 如何用java實現ftp客戶端程序

FTP 的主要操作都是基於各種命令基礎之上的。常用的命令有: · 設置傳輸模式,它包括ASCⅡ(文本) 和BINARY 二進制模式; · 目錄操作,改變或顯示遠程計算機的當前目錄(cd、dir/ls 命令); · 連接操作,open命令用於建立同遠程計算機的連接;close命令用於關閉連接; · 發送操作,put命令用於傳送文件到遠程計算機;mput 命令用於傳送多個文件到遠程計算機; · 獲取操作,get命令用於接收一個文件;mget命令用於接收多個文件。 編程思路 根據FTP 的工作原理,在主函數中建立一個伺服器套接字埠,等待客戶端請求,一旦客戶端請求被接受,伺服器程序就建立一個伺服器分線程,處理客戶端的命令。如果客戶端需要和伺服器端進行文件的傳輸,則建立一個新的套接字連接來完成文件的操作。 編程技巧說明 http://www.jacken.com.cn/Programming/Java/2008-10-24/Java-.html

❽ java中怎麼實現ftp文件傳輸

packagecom.quantongfu.ftp.ftp;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.util.List;

importorg.apache.commons.net.ftp.FTPReply;
importorg.apache.log4j.Logger;
importorg.apache.log4j.net.SocketServer;

importcom.quantongfu.conf.FtpConf;

/**
*@項目名稱:telinSyslog
*@文件名稱:Ftp.java
*@創建日期:2015年9月14日下午3:22:08
*@功能描述:ftp實體類,用於連接,上傳
*@修訂記錄:
*/
publicclassFtp{
privatestaticLoggerlogger=Logger.getLogger(Ftp.class);
privateFTPClientftp;

/**
*
*@parampath
*上傳到ftp伺服器哪個路徑下
*@paramaddr
*地址
*@paramport
*埠號
*@paramusername
*用戶名
*@parampassword
*密碼
*@return
*@throwsException
*/
publicbooleanconnect()throwsException{
booleanresult=false;
ftp=newFTPClient();
intreply;
ftp.connect(FtpConf.FTP_HOST,FtpConf.FTP_PORT);
ftp.login(FtpConf.FTP_USER_NAME,FtpConf.FTP_PASSWORD);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setDataTimeout(60000);
reply=ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
returnresult;
}
if(FtpConf.IS_FTP_DIRECTORY){
ftp.changeWorkingDirectory(FtpConf.FTP_DIRECTORY);
}
result=true;
returnresult;
}

/**
*
*@paramfiles
*上傳的文件
*@throwsException
*/
publicbooleanupload(Filefile)throwsIOException{
FileInputStreaminput=null;
try{
input=newFileInputStream(file);
booleanb=ftp.storeFile(file.getName()+".tmp",input);
if(b){
b=ftp.rename(file.getName()+".tmp",file.getName());
}
returnb;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}finally{
if(input!=null){
input.close();
}
}
}

/**
*
*@paramfiles
*上傳的文件
*@throwsException
*/
publicbooleanupload(ServerSocketserver,Filefile)throwsException{
FileInputStreaminput=null;
try{
if(!file.exists()){
returntrue;
}
input=newFileInputStream(file);
booleanb=ftp.storeFile(server,file.getName()+".tmp",input);
if(b){
b=ftp.rename(file.getName()+".tmp",file.getName());
if(b){
file.delete();
}
}
returnb;
}catch(Exceptione){
logger.error("ftperror"+e.getMessage());
returnfalse;
}finally{
if(input!=null){
try{
input.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
/*斷開連接*/
publicvoiddisConnect(){
try{
if(ftp!=null){
ftp.disconnect();
}
}catch(IOExceptione){
e.printStackTrace();
}

}
/*獲取連接*/
publicstaticFtpgetFtp(){
Ftpftp=newFtp();
try{
ftp.connect();
}catch(Exceptione){
logger.error("FTP連接異常"+e.getMessage());
e.printStackTrace();
}
returnftp;
}
/*重連*/
publicFtpreconnect(){
disConnect();
returngetFtp();
}
}

使用Apache FtpClient jar包,獲取jar : http://commons.apache.org/net/

❾ 如何用Java實現FTP伺服器

1.使用的FileZillaServer開源免費軟體,安裝過後建立的本地FTP伺服器。2.使用的apache上下載FTP工具包,引用到工程目錄中。3.IDE,Eclipse,JDK6上傳和下載目錄的實現原理:對每一個層級的目錄進行判斷,是為目錄類型、還是文件類型。如果為目錄類型,採用遞歸調用方法,檢查到最底層的目錄為止結束。如果為文件類型,則調用上傳或者下載方法對文件進行上傳或者下載操作。貼出代碼:(其中有些沒有代碼,可以看看,還是很有用處的)!

❿ 求用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);

}
}}

熱點內容
下沉演算法 發布:2024-10-05 21:59:43 瀏覽:995
資料庫管理系統的開發 發布:2024-10-05 21:58:02 瀏覽:139
人員最低配置方案怎麼寫 發布:2024-10-05 21:56:26 瀏覽:765
智邦國際伺服器ip 發布:2024-10-05 21:47:37 瀏覽:596
python英文怎麼讀 發布:2024-10-05 21:47:02 瀏覽:145
魔獸世界退役伺服器有什麼用處 發布:2024-10-05 20:50:00 瀏覽:195
新車配置不符怎麼投訴 發布:2024-10-05 20:49:00 瀏覽:389
編譯的html文件 發布:2024-10-05 20:48:58 瀏覽:161
python自學網站 發布:2024-10-05 20:46:08 瀏覽:19
存儲在rom中的數據當計算機斷電後 發布:2024-10-05 20:43:46 瀏覽:10