java文件上传至ftp服务器的方法
用java实现ftp文件上传。我使用的是commons-net-1.4.1.zip。其中包含了众多的java网络编程的工具包。
1.把commons-net-1.4.1.jar包加载到项目工程中去。
2.看如下代码:
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPReply;
publicclassFileTool{
/**
*Description:向FTP服务器上传文件
*@Version1.0
*@paramurlFTP服务器hostname
*@paramportFTP服务器端口
*@paramusernameFTP登录账号
*@parampasswordFTP登录密码
*@parampathFTP服务器保存目录
*@paramfilename上传到FTP服务器上的文件名
*@paraminput输入流
*@return成功返回true,否则返回false*
*/
publicstaticbooleanuploadFile(Stringurl,//FTP服务器hostname
intport,//FTP服务器端口
Stringusername,//FTP登录账号
Stringpassword,//FTP登录密码
Stringpath,//FTP服务器保存目录
Stringfilename,//上传到FTP服务器上的文件名
InputStreaminput//输入流
){
booleansuccess=false;
FTPClientftp=newFTPClient();
ftp.setControlEncoding("GBK");
try{
intreply;
ftp.connect(url,port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username,password);//登录
reply=ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
returnsuccess;
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.makeDirectory(path);
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename,input);
input.close();
ftp.logout();
success=true;
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(ftp.isConnected()){
try{
ftp.disconnect();
}catch(IOExceptionioe){
}
}
}
returnsuccess;
}
/**
*将本地文件上传到FTP服务器上*
*/
publicstaticvoidupLoadFromProduction(Stringurl,//FTP服务器hostname
intport,//FTP服务器端口
Stringusername,//FTP登录账号
Stringpassword,//FTP登录密码
Stringpath,//FTP服务器保存目录
Stringfilename,//上传到FTP服务器上的文件名
Stringorginfilename//输入流文件名
){
try{
FileInputStreamin=newFileInputStream(newFile(orginfilename));
booleanflag=uploadFile(url,port,username,password,path,filename,in);
System.out.println(flag);
}catch(Exceptione){
e.printStackTrace();
}
}
//测试
publicstaticvoidmain(String[]args){
upLoadFromProduction("192.168.13.32",21,"hanshibo","han","韩士波测试","hanshibo.doc","E:/temp/H2数据库使用.doc");
}
}
3.直接运行。即可把指定的文件上传到ftp服务器.有需要jar包的可以到我的资源中去下载。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。