当前位置:首页 » 文件传输 » 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) {;} } }