当前位置:首页 » 文件管理 » javaftpdemo

javaftpdemo

发布时间: 2022-11-14 19:55:05

java ftp怎么实现java ftp方式的断点续传

运用类的办法,编程人员能够长途登录到FTP服务器,罗列该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵 盖了简直一切FTP的功用,FtpClient的实例变量保留了有关树立"署理"的各种信息。下面给出了这些实例变量:

public static boolean useFtpProxy

这个变量用于标明FTP传输过程中是不是运用了一个署理,因此,它实际上是一个符号,此符号若为TRUE,标明运用了一个署理主机。

public static String ftpProxyHost

此变量只要在变量useFtpProxy为TRUE时才有用,用于保留署理主机名。

public static int ftpProxyPort

此变量只要在变量useFtpProxy为TRUE时才有用,用于保留署理主机的端口地址。

FtpClient有三种不同方式的结构函数,如下所示:

1、public FtpClient(String hostname,int port)

此结构函数运用给出的主机名和端口号树立一条FTP衔接。

2、public FtpClient(String hostname)

此结构函数运用给出的主机名树立一条FTP衔接,运用默许端口号。

3、FtpClient()

此结构函数将创立一FtpClient类,但不树立FTP衔接。这时,FTP衔接能够用openServer办法树立。

一旦树立了类FtpClient,就能够用这个类的办法来翻开与FTP服务器的衔接。类ftpClient供给了如下两个可用于翻开与FTP服务器之间的衔接的办法。

public void openServer(String hostname)

这个办法用于树立一条与指定主机上的FTP服务器的衔接,运用默许端口号。

❷ 用java编写ftp客户端这样的网络程序需用到Java的什么知识

会socket编程就可以了
我给你个测试:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import sun.net.ftp.*;

//FTP连接与浏览

public class FtpClientDemo extends JFrame{

JTextField jtfServer; //输入Ftp服务器地址
JTextField jtfUser; //输入用户名
JPasswordField jtfPass; //输入密码
JButton jbConnect; //连接按钮
JButton jbDisconnect; //断开按钮
JTextArea jtaShowFiles; //显示服务器目录与文件
FtpClient ftpClient;

public FtpClientDemo(){
super("FTP连接与浏览"); //调用父类构造函数

jtfServer=new JTextField(13); //实例化组件
jtfUser=new JTextField(8);
jtfPass=new JPasswordField(8);
jbConnect=new JButton("连接");
jbDisconnect=new JButton("断开");
jtaShowFiles=new JTextArea();

Container container=getContentPane(); //得到容器
JPanel panel=new JPanel(); //实例化面板
panel.add(new JLabel("地址")); //增加组件到面板上
panel.add(jtfServer);
panel.add(new JLabel("用户名"));
panel.add(jtfUser);
panel.add(new JLabel("密码"));
panel.add(jtfPass);
container.add(panel,BorderLayout.NORTH); //增加组件到容器上
JScrollPane jsp=new JScrollPane(jtaShowFiles);
container.add(jsp,BorderLayout.CENTER);
panel=new JPanel();
panel.add(jbConnect);
panel.add(jbDisconnect);
container.add(panel,BorderLayout.SOUTH);

jbConnect.addActionListener(new ActionListener(){ //连接按钮事件处理
public void actionPerformed(ActionEvent ent){
connectServer(); //调用连接到服务器的方法
}
});

jbDisconnect.addActionListener(new ActionListener(){ //断开按钮事件处理
public void actionPerformed(ActionEvent ent){
disconnectServer(); //调用断开与服务器连接的方法
}
});

setSize(460,260); //设置窗口尺寸
setVisible(true); //设置窗口可视
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
}

public void connectServer(){
try{
ftpClient = new FtpClient(); //实例化FtpClient对象
String serverAddr=jtfServer.getText(); //得到服务器地址
String user=jtfUser.getText(); //得到用户名
String pass=jtfPass.getPassword().toString(); //得到密码
ftpClient.openServer(serverAddr); //连接到服务器
ftpClient.login(user,pass); //在服务器上注册
InputStream is=ftpClient.list(); //得到服务器目录与文件列表输入流
StringBuffer info=new StringBuffer(); //实例化StringBuffer对象,用于输出信息
int ch;
while ((ch=is.read())>=0){ //未读完列表,则继续
info.append((char)ch); //增加信息
}
jtaShowFiles.setText(new String(info)); //显示信息
is.close(); //关闭输入流
}
catch (IOException ex){
JOptionPane.showMessageDialog(FtpClientDemo.this,ex.getMessage()); //显示提示信息
ex.printStackTrace(); //在命令行窗口输出出错信息
}

}

public void disconnectServer(){
try{
ftpClient.closeServer(); //关闭与服务器的连接
}
catch (IOException ex){
ex.printStackTrace();
}
}

public static void main(String[] args){
new FtpClientDemo();
}
}

❸ 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访问

在主函数中,完成服务器端口的侦听和服务线程的创建。我们利用一个静态字符串变量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){}
}

❺ 怎么用Java实现FTP上传

sun.net.ftp.FtpClient.,该类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立"代理"的各种信息。下面给出了这些实例变量:
public static boolean useFtpProxy
这个变量用于表明FTP传输过程中是否使用了一个代理,因此,它实际上是一个标记,此标记若为TRUE,表明使用了一个代理主机。
public static String ftpProxyHost
此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机名。
public static int ftpProxyPort此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机的端口地址。
FtpClient有三种不同形式的构造函数,如下所示:
1、public FtpClient(String hostname,int port)
此构造函数利用给出的主机名和端口号建立一条FTP连接。
2、public FtpClient(String hostname)
此构造函数利用给出的主机名建立一条FTP连接,使用默认端口号。
3、FtpClient()
此构造函数将创建一FtpClient类,但不建立FTP连接。这时,FTP连接可以用openServer方法建立。
一旦建立了类FtpClient,就可以用这个类的方法来打开与FTP服务器的连接。类ftpClient提供了如下两个可用于打开与FTP服务器之间的连接的方法。
public void openServer(String hostname)
这个方法用于建立一条与指定主机上的FTP服务器的连接,使用默认端口号。
public void openServer(String host,int port)
这个方法用于建立一条与指定主机、指定端口上的FTP服务器的连接。
打开连接之后,接下来的工作是注册到FTP服务器。这时需要利用下面的方法。
public void login(String username,String password)
此方法利用参数username和password登录到FTP服务器。使用过Intemet的用户应该知道,匿名FTP服务器的登录用户名为anonymous,密码一般用自己的电子邮件地址。
下面是FtpClient类所提供的一些控制命令。
public void cd(String remoteDirectory):该命令用于把远程系统上的目录切换到参数remoteDirectory所指定的目录。
public void cdUp():该命令用于把远程系统上的目录切换到上一级目录。
public String pwd():该命令可显示远程系统上的目录状态。
public void binary():该命令可把传输格式设置为二进制格式。
public void ascii():该命令可把传输协议设置为ASCII码格式。
public void rename(String string,String string1):该命令可对远程系统上的目录或者文件进行重命名操作。
除了上述方法外,类FtpClient还提供了可用于传递并检索目录清单和文件的若干方法。这些方法返回的是可供读或写的输入、输出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回与远程机器上当前目录相对应的输入流。
public TelnetInputStream get(String filename)
获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
public TelnetOutputStream put(String filename)
以写方式打开一输出流,通过这一输出流把文件filename传送到远程计算机

package myUtil;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* ftp上传,下载

*
* @author why 2009-07-30
*
*/
public class FtpUtil {
private String ip = "";
private String username = "";
private String password = "";
private int port = -1;
private String path = "";
FtpClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
public FtpUtil(String serverIP, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
public FtpUtil(String serverIP, int port, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
/**
* 连接ftp服务器
*
* @throws IOException
*/
public boolean connectServer() {
ftpClient = new FtpClient();
try {
if (this.port != -1) {
ftpClient.openServer(this.ip, this.port);
} else {
ftpClient.openServer(this.ip);
}
ftpClient.login(this.username, this.password);
if (this.path.length() != 0) {
ftpClient.cd(this.path);// path是ftp服务下主目录的子目录
}
ftpClient.binary();// 用2进制上传、下载
System.out.println("已登录到\"" + ftpClient.pwd() + "\"目录");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 断开与ftp服务器连接
*
* @throws IOException
*/
public boolean closeServer() {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
System.out.println("已从服务器断开");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 检查文件夹在当前目录下是否存在
*
* @param dir
*@return
*/
private boolean isDirExist(String dir) {
String pwd = "";
try {
pwd = ftpClient.pwd();
ftpClient.cd(dir);
ftpClient.cd(pwd);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 在当前目录下创建文件夹
*
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir) {
try {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); // sign
s.countTokens();
String pathName = ftpClient.pwd();
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
/**
* ftp上传 如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
*
* @param filename
* 要上传的文件(或文件夹)名
* @return
* @throws Exception
*/
public boolean upload(String filename) {
String newname = "";
if (filename.indexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1);
} else {
newname = filename;
}
return upload(filename, newname);
}
/**
* ftp上传 如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
*
* @param fileName
* 要上传的文件(或文件夹)名
* @param newName
* 服务器段要生成的文件(或文件夹)名
* @return
*/
public boolean upload(String fileName, String newName) {
try {
String savefilename = new String(fileName.getBytes("GBK"),
"GBK");
File file_in = new File(savefilename);// 打开本地待长传的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
}
if (file_in.isDirectory()) {
upload(file_in.getPath(), newName, ftpClient.pwd());
} else {
uploadFile(file_in.getPath(), newName);
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 真正用于上传的方法
*
* @param fileName
* @param newName
* @param path
* @throws Exception
*/
private void upload(String fileName, String newName, String path)
throws Exception {
String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
File file_in = new File(savefilename);// 打开本地待长传的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
}
if (file_in.isDirectory()) {
if (!isDirExist(newName)) {
createDir(newName);
}
ftpClient.cd(newName);
File sourceFile[] = file_in.listFiles();
for (int i = 0; i < sourceFile.length; i++) {
if (!sourceFile[i].exists()) {
continue;
}
if (sourceFile[i].isDirectory()) {
this.upload(sourceFile[i].getPath(), sourceFile[i]
.getName(), path + "/" + newName);
} else {
this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
.getName());
}
}
} else {
uploadFile(file_in.getPath(), newName);
}
ftpClient.cd(path);
}
/**
* upload 上传文件
*
* @param filename
* 要上传的文件名
* @param newname
* 上传后的新文件名
* @return -1 文件不存在 >=0 成功上传,返回文件的大小
* @throws Exception
*/
public long uploadFile(String filename, String newname) throws Exception {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 从ftp下载文件到本地
*
* @param filename
* 服务器上的文件名
* @param newfilename
* 本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
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 (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相对于当前连接目录的某个目录下所有文件列表
*
* @param path
* @return
*/
public List getFileList(String path) {
List list = new ArrayList();
DataInputStream dis;
try {
dis = new DataInputStream(ftpClient.nameList(this.path + path));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上传成功!" : "上传失败!");
ftp.closeServer();
/**
* 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删除文件
*/
}
}

❻ java中怎么实现ftp服务器

我知道apache有个commons net包,其中的FTPClient类可以实现客户端和服务之间的文件传输,但是我如果使用这种方式的话,就得将一台服务器上的文件传到我本地,再将这个文件传到另一台服务器上,感觉这中间多了一步操作;

❼ JAVA怎么实现删除远程FTP服务器上的某一文件

一个JAVA 实现FTP功能的代码,包括了服务器的设置模块,并包括有上传文件至FTP的通用方法、下载文件的通用方法以及删除文件、在ftp服务器上传文件夹、检测文件夹是否存在等,里面的有些代码对编写JAVA文件上传或许有参考价值,

(1):Java FTP主文件代码:

package ftpDemo;

import java.io.DataOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import sun.net.TelnetInputStream;

import sun.net.TelnetOutputStream;

import sun.net.ftp.FtpClient;

public class ftpUtil {

// 上传文件至FTP通用方法

public static void upLoadFileFtp(KmConfig kmConfig,InputStream is, String fileName){

try {

String ftpHost = kmConfig.getFtpHost();

int port = kmConfig.getFtpPort();

String userName = kmConfig.getFtpUser();

String passWord = kmConfig.getFtpPassword();

String path = kmConfig.getFtpPath();

FtpClient ftpClient = new FtpClient(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服务器上保存上传文件的路径。

TelnetOutputStream telnetOut = ftpClient.put(fileName);// fileName为上传的文件名

DataOutputStream dataOut = new DataOutputStream(telnetOut);

byte buffer[] = new byte[ * ];

int count = ;

while ((count = is.read(buffer)) != -) {

dataOut.write(buffer, , count);

}

telnetOut.close();

dataOut.close();

ftpClient.closeServer();

} catch (Exception e) {

System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动");

}

}

// 删除文件至FTP通用方法

public static void deleteFileFtp(KmConfig kmConfig,String fileName){

try {

String ftpHost = kmConfig.getFtpHost();

int port = kmConfig.getFtpPort();

String userName = kmConfig.getFtpUser();

String passWord = kmConfig.getFtpPassword();

String path = kmConfig.getFtpPath();

FtpClient ftpClient = new FtpClient(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 {

ftpClient.sendServer("dele " + fileName + " ");

} catch (Exception e) {

System.out.println("删除文件失败!请检查系统FTP设置,并确认FTP服务启动");

}

ftpClient.closeServer();

} catch (Exception e) {

System.out.println("删除文件失败!");

}

}

// 下载ftp文件

public static void downloadFileFtp(KmConfig kmConfig,String fileName, String clientFileName, OutputStream outputStream){

try {

String ftpHost = kmConfig.getFtpHost();

int port = kmConfig.getFtpPort();

String userName = kmConfig.getFtpUser();

String passWord = kmConfig.getFtpPassword();

String path = kmConfig.getFtpPath();

FtpClient ftpClient = new FtpClient(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 {

TelnetInputStream in = ftpClient.get(fileName);

byte[] bytes = new byte[];

int cnt=;

while ((cnt=in.read(bytes,,bytes.length)) != -) {

outputStream.write(bytes, , cnt);

}

outputStream.close();

in.close();

} catch (Exception e) {

ftpClient.closeServer();

e.printStackTrace();

}

ftpClient.closeServer();

} catch (Exception e) {

System.out.println("下载文件失败!请检查系统FTP设置,并确认FTP服务启动");

}

}

//在ftp服务器上传件文件夹

public boolean createDir(String path,FtpClient ftpClient) throws Exception{

//进入到home文件夹下

ftpClient.cd("/home");

//创建远程文件夹

//远程命令包括

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

//通过远程命令 穿件一个files文件夹

ftpClient.sendServer("MKD "+ path + " ");

//这个方法必须在 这两个方法中间调用 否则 命令不管用

ftpClient.binary();

ftpClient.readServerResponse();

return false;

}

/**

* 检查文件夹是否存在

* @param dir

* @param ftpClient

* @return

*/

public boolean isDirExist(String dir, FtpClient ftpClient) {

try {

ftpClient.cd(dir);

} catch (Exception e) {

return false;

}

return true;

}

}

(2):KmConfig.java代码如下:定义FTP服务器参数,包括登录的用户名密码之类的。

package ftpDemo;

public class KmConfig {

//主机ip

private String FtpHost = "";

//端口号

private int FtpPort;

//ftp用户名

private String FtpUser = "";

//ftp密码

private String FtpPassword = "";

//ftp中的目录

private String FtpPath = "";

public String getFtpHost() {

return FtpHost;

}

public void setFtpHost(String ftpHost) {

FtpHost = ftpHost;

}

public int getFtpPort() {

return FtpPort;

}

public void setFtpPort(int ftpPort) {

FtpPort = ftpPort;

}

public String getFtpUser() {

return FtpUser;

}

public void setFtpUser(String ftpUser) {

FtpUser = ftpUser;

}

public String getFtpPassword() {

return FtpPassword;

}

public void setFtpPassword(String ftpPassword) {

FtpPassword = ftpPassword;

}

public String getFtpPath() {

return FtpPath;

}

public void setFtpPath(String ftpPath) {

FtpPath = ftpPath;

}

}

(3):下面是测试代码:

❽ 关于JAVA FTP连接后文件列表中的中文是乱码

需要设置文件传输的格式,有2中格式 1:asicc 。2:binary格式 也就是二进制格式,并且ftpClient提供了相应的方法,asicc(),barry(),你要在连接ftp的时候加上此方法,ftpClient.binary();

❾ 请问有java上传文件到ftp服务器的demo吗,感激不尽

/**
* 依赖commons-net-3.4.jar, commons-io-2.4.jar
*/
public class FtpUtils {
/**
* 上传
* @param host FTP地址
* @param port 端口ftp默认22,sftp默认23
* @param user ftp用户名
* @param pwd ftp密码
* @param destPath FTP文件保存路径
* @param fileName ftp保存文件名称
* @param file 需要上传的文件
*/
public static void upload(String host, int port,String user, String pwd, String destPath, String fileName, File file){
FTPClient ftp = null;
InputStream fis = null;
try {
//1.建立连接
ftp = new FTPClient();
ftp.connect(host, port);
//2.验证连接地址
int reply = 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 = new FileInputStream(file);
ftp.storeFile(fileName, fis);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
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 (IOException e) {
e.printStackTrace();
}
}
}
}

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

热点内容
pythonforinkeys 发布:2024-05-19 01:55:44 浏览:792
电脑如何局域网共享文件夹 发布:2024-05-19 01:25:01 浏览:68
手机存储越大性能越好吗 发布:2024-05-19 01:14:28 浏览:176
我的世界hyp服务器怎么玩 发布:2024-05-19 00:51:25 浏览:801
手机如何解压百度云文件 发布:2024-05-19 00:32:24 浏览:905
centos使用python 发布:2024-05-18 23:39:48 浏览:869
幻影天龙脚本 发布:2024-05-18 23:38:17 浏览:714
编程的py 发布:2024-05-18 23:36:22 浏览:76
安卓系统怎么改序列号 发布:2024-05-18 23:28:16 浏览:785
c语言中实数 发布:2024-05-18 23:21:03 浏览:897