当前位置:首页 » 文件管理 » ftp复制java

ftp复制java

发布时间: 2022-09-28 20:38:23

⑴ 用java怎么获取ftp上的文件

public class FtpClientUtil {
FtpClient ftpClient;
private String server;
private int port;
private String userName;
private String userPassword;

public FtpClientUtil(String server,int port,String userName,String userPassword)
{
this.server=server;
this.port=port;
this.userName=userName;
this.userPassword=userPassword;
}
/**
* 链接到服务器
* @return
*/
public boolean open()
{
if(ftpClient!=null&&ftpClient.serverIsOpen())
return true;
try
{
ftpClient= new FtpClient();
ftpClient.openServer(server,port);
ftpClient.login(userName, userPassword);
ftpClient.binary();
return true;
}
catch(Exception e)
{
e.printStackTrace();
ftpClient=null;
return false;
}
}

public boolean cd(String dir){
boolean f = false;
try {
ftpClient.cd(dir);
} catch (IOException e) {
Logs.error(e.toString());
return f;
}
return true;
}

/**
* 上传文件到FTP服务器
* @param localPathAndFileName 本地文件目录和文件名
* @param ftpFileName 上传后的文件名
* @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在回自动创建目录
* @throws Exception
*/
public boolean upload(String localDirectoryAndFileName,String ftpFileName,String ftpDirectory)throws Exception {
if(!open())
return false;
FileInputStream is=null;
TelnetOutputStream os=null;
try
{
char ch = ' ';
if (ftpDirectory.length() > 0)
ch = ftpDirectory.charAt(ftpDirectory.length() - 1);
for (; ch == '/' || ch == '\\'; ch = ftpDirectory.charAt(ftpDirectory.length() - 1))
ftpDirectory = ftpDirectory.substring(0, ftpDirectory.length() - 1);

int slashIndex = ftpDirectory.indexOf(47);
int backslashIndex = ftpDirectory.indexOf(92);
int index = slashIndex;
String dirall = ftpDirectory;
if (backslashIndex != -1 && (index == -1 || index > backslashIndex))
index = backslashIndex;
String directory = "";
while (index != -1) {
if (index > 0) {
String dir = dirall.substring(0, index);
directory = directory + "/" + dir;
ftpClient.sendServer("XMKD " + directory + "\r\n");
ftpClient.readServerResponse();
}
dirall = dirall.substring(index + 1);
slashIndex = dirall.indexOf(47);
backslashIndex = dirall.indexOf(92);
index = slashIndex;
if (backslashIndex != -1 && (index == -1 || index > backslashIndex))
index = backslashIndex;
}
ftpClient.sendServer("XMKD " + ftpDirectory + "\r\n");
ftpClient.readServerResponse();

os = ftpClient.put(ftpDirectory + "/"
+ ftpFileName);
File file_in = new File(localDirectoryAndFileName);
is = new FileInputStream(file_in);
byte bytes[] = new byte[1024];
int i;
while ((i = is.read(bytes)) != -1)
os.write(bytes, 0, i);
//清理垃圾

return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
finally
{
if (is != null)
is.close();
if (os != null)
os.close();
}
}
/**
* 从FTP服务器上下载文件并返回下载文件长度
* @param ftpDirectoryAndFileName
* @param localDirectoryAndFileName
* @return
* @throws Exception
*/
public long download(String ftpDirectoryAndFileName,String localDirectoryAndFileName)throws Exception
{
long result = 0;
if(!open())
return result;
TelnetInputStream is = null;
FileOutputStream os = null;
try
{
is = ftpClient.get(ftpDirectoryAndFileName);
java.io.File outfile = new java.io.File(localDirectoryAndFileName);
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 (Exception e)
{
throw e;
}
finally
{
if (is != null)
is.close();
if (os != null)
os.close();

}
return result;
}
/**
* 返回FTP目录下的文件列表
* @param ftpDirectory
* @return
*/
public List<String> getFileNameList(String ftpDirectory)
{
List<String> list = new ArrayList<String>();
if(!open())
return list;
try
{
DataInputStream dis = new DataInputStream(ftpClient.nameList(ftpDirectory));
String filename = "";
while((filename=dis.readLine())!=null)
{
list.add(filename);
}
} catch (Exception e)
{
e.printStackTrace();
}
return list;
}
/**
* 删除FTP上的文件
* @param ftpDirAndFileName
*/
public boolean deleteFile(String ftpDirAndFileName)
{
if(!open())
return false;
ftpClient.sendServer("DELE "+ftpDirAndFileName+"\r\n");
return true;
}
/**
* 删除FTP目录
* @param ftpDirectory
*/
public boolean deleteDirectory(String ftpDirectory)
{
if(!open())
return false;
ftpClient.sendServer("XRMD "+ftpDirectory+"\r\n");
return true;
}
/**
* 关闭链接
*/
public void close()
{
try
{
if(ftpClient!=null&&ftpClient.serverIsOpen())
ftpClient.closeServer();
}catch(Exception e)
{

}
}
}望采纳,谢谢。

⑵ 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/

⑶ 我想登录一个ftp然后把某个目录的所有文件考到另一个ftp的目录的某个文件夹下用java代码实现

用的commons-net包中的FTPClient
ftp1为拷贝目录,ftp2为被拷贝目录
你先登录ftp2调用ftp1,
ftpClient1.changeWorkingDirectory(path);
InputStream inputStream = ftpClient1.retrieveFileStream(file.getName());
用这个代码应该可以从ftp1中获得一个inputStream ,在ftp2中可以做上传操作
目录的话ftp2还要做递归存放到list中,ftp2遍历上传. 其实我也没做这个,希望思路有点帮助,应该可以实现.good luck!~~~

⑷ FTP 复制文件命令

FTP 复制文件命令是get 文件名
1) 说明:显示ftp命令的说明。后面可以加参数,是加需要解释的命令名,不加则显示包含所有命令列表。
2)说明:功能是在本地计算机上运行指定命令。
如! command 其中command就是你要运行的命令,如果不加command这个参数的话,则显示本地命令提示, 这时你输入exit命令就能返回到ftp了。
3)$ macro-ame[args]
说明:执行宏定义macro-name。
4) append
说明:使用当前文件类型设置,将本地文件附加到远程计算机中。大概格式是append local-file [remote-file] 其中local-file是说指定要添加的本地文件。remote-file是说指定要将local-file附加到远程计算机文件,要是省了这个,则是使用本地文件名做远程文件名。

⑸ java如何实现将FTP文件转移到另一个FTP服务器上

你有FTPClient就比较好办,假如你的两台FTP服务器分别为fs1和fs2

在本地开发代码思路如下:

  1. 通过FTPClient连接上fs1,然后下载(可以循环批量下载)到本地服务器,保存到一个临时目录。

  2. 下载完成后,FTPClient断开与fs1的连接,记得必须logout。

  3. 本地服务器通过FileInputStream将刚下载到临时目录的文件读进来,得到一个List<File>集合。

  4. 通过FTPClient连接上fs2,循环List<File>集合,将文件上传至fs2的特定目录,然后清空临时目录,上传完毕后,断开fs2的连接,同样必须logout。

⑹ java如何实现两台ftp服务器之间的文件传输10

�0�2我知道apache有个commons net包,其中的FTPClient类可以实现客户端和服务之间的文件传输,但是我如果使用这种方式的话,就得将一台服务器上的文件传到我本地,再将这个文件传到另一台服务器上,感觉这中间多了一步操作;我想请问大家如何能不通过本机,直接操作两台服务器,将文件从一台服务器传到另一台服务器上,如果有人知道实现方式,希望不吝赐教,谢谢了!问题补充:<div class="quote_title"suziwen 写道</div<div class="quote_div"把JAVA程序放在其中一台FTP服务 器A上,通过A服务器上的JAVA登录到另一台FTP服务器,F代码执行文 件的上传,下载。 / /</div / /谢谢你们的回答,你们说的这种方式我明白。

⑺ java 将服务器内的文件复制

你有FTPClient就比较好办,假如你的两台FTP服务器分别为fs1和fs2
在本地开发代码思路如下:
通过FTPClient连接上fs1,然后下载(可以循环批量下载)到本地服务器,保存到一个临时目录。
下载完成后,FTPClient断开与fs1的连接,记得必须logout。
本地服务器通过FileInputStream将刚下载到临时目录的文件读进来,得到一个List<File>集合。
通过FTPClient连接上fs2,循环List<File>集合,将文件上传至fs2的特定目录,然后清空临时目录,上传完毕后,断开fs2的连接,同样必须logout。

⑻ 如何用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上文件会少1kb

你有FTPClient就比较好办,假如你的两台FTP服务器分别为fs1和fs2
在本地开发代码思路如下:
通过FTPClient连接上fs1,然后下载(可以循环批量下载)到本地服务器,保存到一个临时目录。
下载完成后,FTPClient断开与fs1的连接,记得必须logout。
本地服务器通过FileInputStream将刚下载到临时目录的文件读进来,得到一个List<File>集合。
通过FTPClient连接上fs2,循环List<File>集合,将文件上传至fs2的特定目录,然后清空临时目录,上传完毕后,断开fs2的连接,同样必须logout。

⑽ 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上传输分发软件的一种基本方法

热点内容
安卓系统总是被杀后台怎么办 发布:2024-10-09 07:11:31 浏览:304
花雨庭服务器如何全屏 发布:2024-10-09 06:39:28 浏览:213
密码查看器怎么使用 发布:2024-10-09 06:38:55 浏览:495
sqlrownum 发布:2024-10-09 06:28:53 浏览:383
F模块驱动器编译错误 发布:2024-10-09 06:06:21 浏览:636
脚本亚索集锦 发布:2024-10-09 05:53:30 浏览:877
安卓手机格式化后为什么打不开 发布:2024-10-09 05:52:58 浏览:511
云服务器可以超级计算机吗 发布:2024-10-09 05:51:33 浏览:17
php基本语法手册 发布:2024-10-09 05:34:04 浏览:819
shell脚本累加 发布:2024-10-09 05:33:41 浏览:843