當前位置:首頁 » 文件傳輸 » ftp服務端java代碼
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

ftp服務端java代碼

發布時間: 2023-08-30 19:11:38

Ⅰ JAVA編寫FTP連接報錯java.net.ConnectException: Connection refused: connect FTP

你用的FTPClient引入不對吧,我們項目上都是用的

import org.apache.commons.net.ftp.FTPClient;

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

下面是我們項目上用到的FTP的實現代碼(FTP需要先連接,再登錄,之後就是校驗登錄是否成功),具體代碼如下:

/**
*獲取FTPClient對象
*
*@paramftpHostFTP主機伺服器
*@paramftpPasswordFTP登錄密碼
*@paramftpUserNameFTP登錄用戶名
*@paramftpPortFTP埠默認為21
*@returnFTPClient
*@throwsException
*/
(StringftpHost,StringftpUserName,
StringftpPassword,intftpPort)throwsException{
try{
FTPClientftpClient=newFTPClient();
ftpClient.connect(ftpHost,ftpPort);//連接FTP伺服器
ftpClient.login(ftpUserName,ftpPassword);//登陸FTP伺服器
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
logger.error("未連接到FTP,用戶名或密碼錯誤!");
ftpClient.disconnect();
returnnull;
}else{
logger.info("FTP連接成功!");
returnftpClient;
}
}catch(){
logger.error("FTP的IP地址可能錯誤,請正確配置!");
throwsocketException;
}catch(IOExceptionioException){
logger.error("FTP的埠錯誤,請正確配置!");
throwioException;
}
}

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

}

Ⅲ FTP客戶端程序設計(java)

package jing.upfile;

import sun.net.ftp.*;
import sun.net.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
FTP遠程命令列表<br>
USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT<br>
PASS PASV STOR REST CWD STAT RMD XCUP OPTS<br>
ACCT TYPE APPE RNFR XCWD HELP XRMD STOU AUTH<br>
REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ<br>
QUIT MODE SYST ABOR NLST MKD XPWD MDTM PROT<br>
在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n<br>
ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令<br>
ftpclient.readServerResponse一定要在sendServer後調用<br>
nameList("/test")獲取指目錄下的文件列表<br>
XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯<br>
XRMD刪除目錄<br>
DELE刪除文件<br>
* <p>Title: 使用JAVA操作FTP伺服器(FTP客戶端)</p>
* <p>Description: 上傳文件的類型及文件大小都放到調用此類的方法中去檢測,比如放到前台JAVASCRIPT中去檢測等
* 針對FTP中的所有調用使用到文件名的地方請使用完整的路徑名(絕對路徑開始)。
* </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: 靜靖工作室</p>
* @author 歐朝敬 13873195792
* @version 1.0
*/

public class FtpUpfile {
private FtpClient ftpclient;
private String ipAddress;
private int ipPort;
private String userName;
private String PassWord;
/**
* 構造函數
* @param ip String 機器IP
* @param port String 機器FTP埠號
* @param username String FTP用戶名
* @param password String FTP密碼
* @throws Exception
*/
public FtpUpfile(String ip, int port, String username, String password) throws
Exception {
ipAddress = new String(ip);
ipPort = port;
ftpclient = new FtpClient(ipAddress, ipPort);
//ftpclient = new FtpClient(ipAddress);
userName = new String(username);
PassWord = new String(password);
}

/**
* 構造函數
* @param ip String 機器IP,默認埠為21
* @param username String FTP用戶名
* @param password String FTP密碼
* @throws Exception
*/
public FtpUpfile(String ip, String username, String password) throws
Exception {
ipAddress = new String(ip);
ipPort = 21;
ftpclient = new FtpClient(ipAddress, ipPort);
//ftpclient = new FtpClient(ipAddress);
userName = new String(username);
PassWord = new String(password);
}

/**
* 登錄FTP伺服器
* @throws Exception
*/
public void login() throws Exception {
ftpclient.login(userName, PassWord);
}

/**
* 退出FTP伺服器
* @throws Exception
*/
public void logout() throws Exception {
//用ftpclient.closeServer()斷開FTP出錯時用下更語句退出
ftpclient.sendServer("QUIT\r\n");
int reply = ftpclient.readServerResponse(); //取得伺服器的返回信息
}

/**
* 在FTP伺服器上建立指定的目錄,當目錄已經存在的情下不會影響目錄下的文件,這樣用以判斷FTP
* 上傳文件時保證目錄的存在目錄格式必須以"/"根目錄開頭
* @param pathList String
* @throws Exception
*/
public void buildList(String pathList) throws Exception {
ftpclient.ascii();
StringTokenizer s = new StringTokenizer(pathList, "/"); //sign
int count = s.countTokens();
String pathName = "";
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpclient.sendServer("XMKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
}
int reply = ftpclient.readServerResponse();
}
ftpclient.binary();
}

/**
* 取得指定目錄下的所有文件名,不包括目錄名稱
* 分析nameList得到的輸入流中的數,得到指定目錄下的所有文件名
* @param fullPath String
* @return ArrayList
* @throws Exception
*/
public ArrayList fileNames(String fullPath) throws Exception {
ftpclient.ascii(); //注意,使用字元模式
TelnetInputStream list = ftpclient.nameList(fullPath);
byte[] names = new byte[2048];
int bufsize = 0;
bufsize = list.read(names, 0, names.length); //從流中讀取
list.close();
ArrayList namesList = new ArrayList();
int i = 0;
int j = 0;
while (i < bufsize /*names.length*/) {
//char bc = (char) names;
//System.out.println(i + " " + bc + " : " + (int) names);
//i = i + 1;
if (names == 10) { //字元模式為10,二進制模式為13
//文件名在數據中開始下標為j,i-j為文件名的長度,文件名在數據中的結束下標為i-1
//System.out.write(names, j, i - j);
//System.out.println(j + " " + i + " " + (i - j));
String tempName = new String(names, j, i - j);
namesList.add(tempName);
//System.out.println(temp);
// 處理代碼處
//j = i + 2; //上一次位置二進制模式
j = i + 1; //上一次位置字元模式
}
i = i + 1;
}
return namesList;
}

/**
* 上傳文件到FTP伺服器,destination路徑以FTP伺服器的"/"開始,帶文件名、
* 上傳文件只能使用二進制模式,當文件存在時再次上傳則會覆蓋
* @param source String
* @param destination String
* @throws Exception
*/
public void upFile(String source, String destination) throws Exception {
buildList(destination.substring(0, destination.lastIndexOf("/")));
ftpclient.binary(); //此行代碼必須放在buildList之後
TelnetOutputStream ftpOut = ftpclient.put(destination);
TelnetInputStream ftpIn = new TelnetInputStream(new
FileInputStream(source), true);
byte[] buf = new byte[204800];
int bufsize = 0;
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
ftpIn.close();
ftpOut.close();

}

/**
* JSP中的流上傳到FTP伺服器,
* 上傳文件只能使用二進制模式,當文件存在時再次上傳則會覆蓋
* 位元組數組做為文件的輸入流,此方法適用於JSP中通過
* request輸入流來直接上傳文件在RequestUpload類中調用了此方法,
* destination路徑以FTP伺服器的"/"開始,帶文件名
* @param sourceData byte[]
* @param destination String
* @throws Exception
*/
public void upFile(byte[] sourceData, String destination) throws Exception {
buildList(destination.substring(0, destination.lastIndexOf("/")));
ftpclient.binary(); //此行代碼必須放在buildList之後
TelnetOutputStream ftpOut = ftpclient.put(destination);
ftpOut.write(sourceData, 0, sourceData.length);
// ftpOut.flush();
ftpOut.close();
}

/**
* 從FTP文件伺服器上下載文件SourceFileName,到本地destinationFileName
* 所有的文件名中都要求包括完整的路徑名在內
* @param SourceFileName String
* @param destinationFileName String
* @throws Exception
*/
public void downFile(String SourceFileName, String destinationFileName) throws
Exception {
ftpclient.binary(); //一定要使用二進制模式
TelnetInputStream ftpIn = ftpclient.get(SourceFileName);
byte[] buf = new byte[204800];
int bufsize = 0;
FileOutputStream ftpOut = new FileOutputStream(destinationFileName);
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
ftpOut.close();
ftpIn.close();
}

/**
*從FTP文件伺服器上下載文件,輸出到位元組數組中
* @param SourceFileName String
* @return byte[]
* @throws Exception
*/
public byte[] downFile(String SourceFileName) throws
Exception {
ftpclient.binary(); //一定要使用二進制模式
TelnetInputStream ftpIn = ftpclient.get(SourceFileName);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
byte[] buf = new byte[204800];
int bufsize = 0;

while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
byteOut.write(buf, 0, bufsize);
}
byte[] return_arraybyte = byteOut.toByteArray();
byteOut.close();
ftpIn.close();
return return_arraybyte;
}

/**調用示例
* FtpUpfile fUp = new FtpUpfile("192.168.0.1", 21, "admin", "admin");
* fUp.login();
* fUp.buildList("/adfadsg/sfsdfd/cc");
* String destination = "/test.zip";
* fUp.upFile("C:\\Documents and Settings\\Administrator\\My Documents\\sample.zip",destination);
* ArrayList filename = fUp.fileNames("/");
* for (int i = 0; i < filename.size(); i++) {
* System.out.println(filename.get(i).toString());
* }
* fUp.logout();
* @param args String[]
* @throws Exception
*/
public static void main(String[] args) throws Exception {
FtpUpfile fUp = new FtpUpfile("192.150.189.22", 21, "admin", "admin");
fUp.login();
/* fUp.buildList("/adfadsg/sfsdfd/cc");
String destination = "/test/SetupDJ.rar";
fUp.upFile(
"C:\\Documents and Settings\\Administrator\\My Documents\\SetupDJ.rar",
destination);
ArrayList filename = fUp.fileNames("/");
for (int i = 0; i < filename.size(); i++) {
System.out.println(filename.get(i).toString());
}

fUp.downFile("/sample.zip", "d:\\sample.zip");
*/
FileInputStream fin = new FileInputStream(
"C:\\AAA.TXT");
byte[] data = new byte[20480];
fin.read(data, 0, data.length);
fUp.upFile(data, "/test/BBB.exe");
fUp.logout();
System.out.println("程序運行完成!");
/*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刪除文件
*/
}
}

Ⅳ 求每日定時在伺服器的FTP上取數據文件的源碼(JAVA)

這個是可以向伺服器端發送文字的程序,就是在客戶端發送一句hello在伺服器也可以接受到hello,這個程序可以修改一下就可以了。具體修改方法是增加一個定時器,然後把字元流改成位元組流,現在有點忙,你先研究啊,近兩天幫你寫寫看。
伺服器端:
import java.net.*;
import java.io.*;

public class DateServer {
public static void main(String[] args) {
ServerSocket server=null;

try{
server=new ServerSocket(6666);
System.out.println(
"Server start on port 6666...");
while(true){
Socket socket=server.accept();
new SocketHandler(socket).start();
/*
PrintWriter out=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
out.println(new java.util.Date().toLocaleString());
out.close();
*/
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(server!=null) {
try{
server.close();
}catch(Exception ex){}
}
}
}
}

class SocketHandler extends Thread {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket=socket;
}
public void run() {
try{
PrintWriter out=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
out.println(
new java.util.Date().
toLocaleString());
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
客戶端:
package com.briup;

import java.io.*;
import java.net.*;

public class FtpClient {
public static void main(String[] args) {
if(args.length==0) {
System.out.println("Usage:java FtpClient file_path");
System.exit(0);
}
File file=new File(args[0]);
if(!file.exists()||!file.canRead()) {
System.out.println(args[0]+" doesn't exist or can not read.");
System.exit(0);
}

Socket socket=null;

try{
socket=new Socket(args[1],Integer.parseInt(args[2]));
BufferedInputStream in=new BufferedInputStream(
new FileInputStream(file)
);
BufferedOutputStream out=new BufferedOutputStream(
socket.getOutputStream()
);
byte[] buffer=new byte[1024*8];
int i=-1;
while((i=in.read(buffer))!=-1) {
out.write(buffer,0,i);
}
System.out.println(socket.getInetAddress().getHostAddress()+" send file over.");
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}finally{
if(socket!=null) {
try{
socket.close();
}catch(Exception ex){}
}
}
}
}

Ⅳ 如何用JAVA實現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 != 0) {
initDir = args[0];
}else{ initDir = "c:";}
int i = 1;
try{
System.out.println("ftp server started!");
//監聽21號埠
ServerSocket s = new ServerSocket(21);
for(;;){
//接受客戶端請求
Socket incoming = s.accept();
//創建服務線程
new ftpServer(incoming,i).start();
i++;
}
}catch(Exception e){}
}

Ⅵ 求FTP CLIENT源碼(java)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;

public class FtpClientDemo {
public static int BUFFER_SIZE = 10240;
private FtpClient m_client;
// set the values for your server
private String host = "";
private String user = "";
private String password = "";
private String sDir = "";
private String m_sLocalFile = "";
private String m_sHostFile = "";
public FtpClientDemo() {
try {
System.out.println("Connecting to host " + host);
m_client = new FtpClient(host);
m_client.login(user, password);
System.out.println("User " + user + " login OK");
System.out.println(m_client.welcomeMsg);
m_client.cd(sDir);
System.out.println("Directory: " + sDir);
m_client.binary();
System.out.println("Success.");
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
protected void disconnect() {
if (m_client != null) {
try {
m_client.closeServer();
} catch (IOException ex) {
}
m_client = null;
}
}
public static int getFileSize(FtpClient client, String fileName)
throws IOException {
TelnetInputStream lst = client.list();
String str = "";
fileName = fileName.toLowerCase();
while (true) {
int c = lst.read();
char ch = (char) c;
if (c < 0 || ch == '\n') {
str = str.toLowerCase();
if (str.indexOf(fileName) >= 0) {
StringTokenizer tk = new StringTokenizer(str);
int index = 0;
while (tk.hasMoreTokens()) {
String token = tk.nextToken();
if (index == 4)
try {
return Integer.parseInt(token);
} catch (NumberFormatException ex) {
return -1;
}
index++;
}
}
str = "";
}
if (c <= 0)
break;
str += ch;
}
return -1;
}
protected void getFile() {
if (m_sLocalFile.length() == 0) {
m_sLocalFile = m_sHostFile;
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
int size = getFileSize(m_client, m_sHostFile);
if (size > 0) {
System.out.println("File " + m_sHostFile + ": " + size
+ " bytes");
System.out.println(size);
} else
System.out.println("File " + m_sHostFile + ": size unknown");
FileOutputStream out = new FileOutputStream(m_sLocalFile);
InputStream in = m_client.get(m_sHostFile);
int counter = 0;
while (true) {
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
}
out.close();
in.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
protected void putFile() {
if (m_sLocalFile.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(m_sLocalFile);
int size = (int) f.length();
System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(m_sLocalFile);
OutputStream out = m_client.put(m_sHostFile);
int counter = 0;
while (true) {
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
public static void main(String argv[]) {
new FtpClientDemo();
}
}

Ⅶ java FTP下載文件在代碼中如何實現知道下載完成

(KmConfigkmConfig,StringfileName,StringclientFileName,OutputStreamoutputStream){
try{
StringftpHost=kmConfig.getFtpHost();
intport=kmConfig.getFtpPort();
StringuserName=kmConfig.getFtpUser();
StringpassWord=kmConfig.getFtpPassword();
Stringpath=kmConfig.getFtpPath();
FtpClientftpClient=newFtpClient(ftpHost,port);//ftpHost為FTP伺服器的IP地址,port為FTP伺服器的登陸埠,ftpHost為String型,port為int型。
ftpClient.login(userName,passWord);//userName、passWord分別為FTP伺服器的登陸用戶名和密碼
ftpClient.binary();
ftpClient.cd(path);//path為FTP伺服器上保存上傳文件的路徑。
try{
TelnetInputStreamin=ftpClient.get(fileName);
byte[]bytes=newbyte[1024];
intcnt=0;
while((cnt=in.read(bytes,0,bytes.length))!=-1){
outputStream.write(bytes,0,cnt);
}
//##############################################
//這里文件就已經下載完了,自己理解一下
//#############################################

outputStream.close();
in.close();
}catch(Exceptione){
ftpClient.closeServer();
e.printStackTrace();
}
ftpClient.closeServer();
}catch(Exceptione){
System.out.println("下載文件失敗!請檢查系統FTP設置,並確認FTP服務啟動");
}
}

Ⅷ 怎麼用java代碼創建ftp用戶和密碼

這個取決於你的ftp伺服器,IIS,Mozila...規則不一樣

Ⅸ 如何在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) {;} } }