当前位置:首页 » 文件传输 » java链接ftp程序
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

java链接ftp程序

发布时间: 2022-05-08 10:31:02

1. java 连接ftp是主动模式还是被动模式

一.FTP的PORT(主动模式)和PASV(被动模式)
1.
PORT(主动模式)
PORT中文称为主动模式,工作的原理:
FTP客户端连接到FTP服务器的21端口,发送用户名和密码登录,登录成功后要list列表或者读取数据时,客户端随机开放一个端口(1024以上),发送
PORT命令到FTP服务器,告诉服务器客户端采用主动模式并开放端口;FTP服务器收到PORT主动模式命令和端口号后,通过服务器的20端口和客户端开放的端口连接,发送数据.
2.
PASV(被动模式)
PASV是Passive的缩写,中文成为被动模式,工作原理:FTP客户端连接到FTP服务器的21端口,发送用户名和密码登录,登录成功后要list列表或者读取数据时,发送PASV命令到FTP服务器,
服务器在本地随机开放一个端口(1024以上),然后把开放的端口告诉客户端,
客户端再连接到服务器开放的端口进行数据传输。
二.两种模式的比较
从上面的运行原来看到,主动模式和被动模式的不同简单概述为:
主动模式传送数据时是“服务器”连接到“客户端”的端口;被动模式传送数据是“客户端”连接到“服务器”的端口。
主动模式需要客户端必须开放端口给服务器,很多客户端都是在防火墙内,开放端口给FTP服务器访问比较困难。
被动模式只需要服务器端开放端口给客户端连接就行了。
三.不同工作模式的网络设置
实际项目中碰到的问题是,FTP的客户端和服务器分别在不同网络,两个网络之间有至少4层的防火墙,服务器端只开放了21端口,
客户端机器没开放任何端口。FTP客户端连接采用的被动模式,结果客户端能登录成功,但是无法LIST列表和读取数据。很明显,是因为服务器端没开放被动模式下的随机端口导致。
由于被动模式下,服务器端开放的端口随机,但是防火墙要不能全部开放,解决的方案是,在ftp服务器配置被动模式下开放随机端口在
50000-60000之间(范围在ftp服务器软件设置,可以设置任意1024上的端口段),然后在防火墙设置规则,开放服务器端50000-60000之间的端口端。
主动模式下,客户端的FTP软件设置主动模式开放的端口段,在客户端的防火墙开放对应的端口段。
四.如何设置
工作模式
实时上FTP服务器一般都支持主动和被动模式,连接采用何种模式是有FTP客户端软件决定。

2. 如何用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){}
}

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

}
}}

4. 如何用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

5. 怎么用java实现ftp的登陆

/**
*依赖commons-net-3.4.jar,commons-io-2.4.jar
*/
publicclassFtpUtils{
/**
*上传
*@paramhostFTP地址
*@paramport端口ftp默认22,sftp默认23
*@paramuserftp用户名
*@parampwdftp密码
*@paramdestPathFTP文件保存路径
*@paramfileNameftp保存文件名称
*@paramfile需要上传的文件
*/
publicstaticvoipload(Stringhost,intport,Stringuser,Stringpwd,StringdestPath,StringfileName,Filefile){
FTPClientftp=null;
InputStreamfis=null;
try{
//1.建立连接
ftp=newFTPClient();
ftp.connect(host,port);
//2.验证连接地址
intreply=ftp.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
return;
}
//3.登录
ftp.login(user,pwd);
//设置上传路径、缓存、字符集、文件类型等
ftp.changeWorkingDirectory(destPath);
ftp.setBufferSize(1024);
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//4.上传
fis=newFileInputStream(file);
ftp.storeFile(fileName,fis);
}catch(SocketExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
IOUtils.closeQuietly(fis);
try{
if(ftp.isAvailable()){
ftp.logout();
}
if(ftp.isConnected()){
ftp.disconnect();
}
//删除上传临时文件
if(null!=file&&file.exists()){
file.delete();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

6. 如何用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);
}

7. 关于java ftp程序

第一;中的ip,
c.getPassword()),是否可以正常连接
第二.getServerIp(),先确定你所要连接的ftp服务器是否可用,
c.getUserName().connect(c,可以用ftp命令在命令行或者用ftp软件测试,在确定help,如果ftp服务器正常可用这个问题很简单呀,name

8. java程序可以成功连接Ftp服务器,但无法上传文件,怎么回事,报错如下,(已设置连接超时时间200s)

我感觉有俩问题,1、连接地址和帐号不是一回事,你最好不要用域名做连接地址,可以用IP地址;2、你是在不行通过空间服务商进入线上后台,如果还不行就联系空间商,可能是他们的问题.果是VPS的话好像要开通ftp某些权限才可以,你只是开通了帐号,能连接,并没有给ftp上传下载的权限,这个我在空间商里面看过教程的,在这没网络不让发连接,你可以在网络搜一下试试,希望能帮助你。

9. 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;
}
}