首页 > 编程知识 正文

javaftp上传下载中文文件(Java上传文件到ftp)

时间:2023-12-19 16:21:16 阅读:317798 作者:QSCF

本文目录一览:

Java FTPClient 连接FTP,上传文件,不能以中文保存

在连接之前设置ftpClient.setControlEncoding("GBK");连接之后再设置是没有作用的。

FTP软件应如何设置才能支持带中文文件名的文件正常上传下载?

ftp上传文件时,必须使用英文字符或数据的文件名才能上传,或者是两个字的汉字才能上传到服务器的话:

1、进入ServerU管理端界面,点击“服务器限制和设置”分类功能按钮,

2、在ServerU服务器限制和设置界面,选择“FTP设置”页签,点击窗口下面的“全局设置”按钮。

3、在打开的“FTP命令属性”界面,去掉最后一行的勾选,即不要勾选”对所有已收发的路径和文件名使用UTF-8编码“。

4、选择“FTP设置”页签,禁用”OPTS UTF8 “,

完成上面的两处改变后,无法上传中文名称的文件的问题应该已经解决了。

怎么用Java实现FTP上传

sun.net..,该类库主要提供了用于建立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上传,下载

*

* @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 + "rn");

} 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");

;

boolean result = ("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");

System.out.println(result ? "上传成功!" : "上传失败!");

;

/**

* 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命令都要加上rn

* ftpclient.sendServer("XMKD /test/bbrn"); //执行服务器上的FTP命令

* ftpclient.readServerResponse一定要在sendServer后调用

* nameList("/test")获取指目录下的文件列表 XMKD建立目录,当目录存在的情况下再次创建目录时报错 XRMD删除目录

* DELE删除文件

*/

}

}

java 实现ftp上传下载,windows下和linux下游何区别?

package com.weixin.util;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.io.RandomAccessFile;

import org.apache.commons.net.PrintCommandListener;

import org.apache.commons.net.;

import org.apache.commons.net.;

import org.apache.commons.net.;

import org.apache.commons.net.;

import com.weixin.constant.DownloadStatus;

import com.weixin.constant.UploadStatus;

/**

 * 支持断点续传的FTP实用类

 * @version 0.1 实现基本断点上传下载

 * @version 0.2 实现上传下载进度汇报

 * @version 0.3 实现中文目录创建及中文文件创建,添加对于中文的支持

 */

public class ContinueFTP {

public FTPClient ftpClient = new FTPClient();

public ContinueFTP(){

//设置将过程中使用到的命令输出到控制台

this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

}

/**

 * 连接到FTP服务器

 * @param hostname 主机名

 * @param port 端口

 * @param username 用户名

 * @param password 密码

 * @return 是否连接成功

 * @throws IOException

 */

public boolean connect(String hostname,int port,String username,String password) throws IOException{

ftpClient.connect(hostname, port);

ftpClient.setControlEncoding("GBK");

if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){

if(ftpClient.login(username, password)){

return true;

}

}

disconnect();

return false;

}

/**

 * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报

 * @param remote 远程文件路径

 * @param local 本地文件路径

 * @return 上传的状态

 * @throws IOException

 */

public DownloadStatus download(String remote,String local) throws IOException{

//设置被动模式

ftpClient.enterLocalPassiveMode();

//设置以二进制方式传输

ftpClient.setFileType();

DownloadStatus result;

//检查远程文件是否存在

FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1"));

if(files.length != 1){

System.out.println("远程文件不存在");

return DownloadStatus.Remote_File_Noexist;

}

long lRemoteSize = files[0].getSize();

File f = new File(local);

//本地存在文件,进行断点下载

if(f.exists()){

long localSize = f.length();

//判断本地文件大小是否大于远程文件大小

if(localSize = lRemoteSize){

System.out.println("本地文件大于远程文件,下载中止");

return DownloadStatus.Local_Bigger_Remote;

}

//进行断点续传,并记录状态

FileOutputStream out = new FileOutputStream(f,true);

ftpClient.setRestartOffset(localSize);

InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));

byte[] bytes = new byte[1024];

long step = lRemoteSize /100;

long process=localSize /step;

int c;

while((c = in.read(bytes))!= -1){

out.write(bytes,0,c);

localSize+=c;

long nowProcess = localSize /step;

if(nowProcess  process){

process = nowProcess;

if(process % 10 == 0)

System.out.println("下载进度:"+process);

//TODO 更新文件下载进度,值存放在process变量中

}

}

in.close();

out.close();

boolean isDo = ftpClient.completePendingCommand();

if(isDo){

result = DownloadStatus.Download_From_Break_Success;

}else {

result = DownloadStatus.Download_From_Break_Failed;

}

}else {

OutputStream out = new FileOutputStream(f);

InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));

byte[] bytes = new byte[1024];

long step = lRemoteSize /100;

long process=0;

long localSize = 0L;

int c;

while((c = in.read(bytes))!= -1){

out.write(bytes, 0, c);

localSize+=c;

long nowProcess = localSize /step;

if(nowProcess  process){

process = nowProcess;

if(process % 10 == 0)

System.out.println("下载进度:"+process);

//TODO 更新文件下载进度,值存放在process变量中

}

}

in.close();

out.close();

boolean upNewStatus = ftpClient.completePendingCommand();

if(upNewStatus){

result = DownloadStatus.Download_New_Success;

}else {

result = DownloadStatus.Download_New_Failed;

}

}

return result;

}

/**

 * 上传文件到FTP服务器,支持断点续传

 * @param local 本地文件名称,绝对路径

 * @param remote 远程文件路径,使用/home/directory1/subdirectory/file.ext 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构

 * @return 上传结果

 * @throws IOException

 */

public UploadStatus upload(String local,String remote) throws IOException{

//设置PassiveMode传输

ftpClient.enterLocalPassiveMode();

//设置以二进制流的方式传输

ftpClient.setFileType();

ftpClient.setControlEncoding("GBK");

UploadStatus result;

//对远程目录的处理

String remoteFileName = remote;

if(remote.contains("/")){

remoteFileName = remote.substring(remote.lastIndexOf("/")+1);

//创建服务器远程目录结构,创建失败直接返回

if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){

return UploadStatus.Create_Directory_Fail;

}

}

//检查远程是否存在文件

FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"),"iso-8859-1"));

if(files.length == 1){

long remoteSize = files[0].getSize();

File f = new File(local);

long localSize = f.length();

if(remoteSize==localSize){

return UploadStatus.File_Exits;

}else if(remoteSize  localSize){

return UploadStatus.Remote_Bigger_Local;

}

//尝试移动文件内读取指针,实现断点续传

result = uploadFile(remoteFileName, f, ftpClient, remoteSize);

//如果断点续传没有成功,则删除服务器上文件,重新上传

if(result == UploadStatus.Upload_From_Break_Failed){

if(!ftpClient.deleteFile(remoteFileName)){

return UploadStatus.Delete_Remote_Faild;

}

result = uploadFile(remoteFileName, f, ftpClient, 0);

}

}else {

result = uploadFile(remoteFileName, new File(local), ftpClient, 0);

}

return result;

}

/**

 * 断开与远程服务器的连接

 * @throws IOException

 */

public void disconnect() throws IOException{

if(ftpClient.isConnected()){

ftpClient.disconnect();

}

}

/**

 * 递归创建远程服务器目录

 * @param remote 远程服务器文件绝对路径

 * @param ftpClient FTPClient对象

 * @return 目录创建是否成功

 * @throws IOException

 */

public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{

UploadStatus status = UploadStatus.Create_Directory_Success;

String directory = remote.substring(0,remote.lastIndexOf("/")+1);

if(!directory.equalsIgnoreCase("/")!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){

//如果远程目录不存在,则递归创建远程服务器目录

int start=0;

int end = 0;

if(directory.startsWith("/")){

start = 1;

}else{

start = 0;

}

end = directory.indexOf("/",start);

while(true){

String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");

if(!ftpClient.changeWorkingDirectory(subDirectory)){

if(ftpClient.makeDirectory(subDirectory)){

ftpClient.changeWorkingDirectory(subDirectory);

}else {

System.out.println("创建目录失败");

return UploadStatus.Create_Directory_Fail;

}

}

start = end + 1;

end = directory.indexOf("/",start);

//检查所有目录是否创建完毕

if(end = start){

break;

}

}

}

return status;

}

/**

 * 上传文件到服务器,新上传和断点续传

 * @param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变

 * @param localFile 本地文件File句柄,绝对路径

 * @param processStep 需要显示的处理进度步进值

 * @param ftpClient FTPClient引用

 * @return

 * @throws IOException

 */

public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{

UploadStatus status;

//显示进度的上传

long step = localFile.length() / 100;

long process = 0;

long localreadbytes = 0L;

RandomAccessFile raf = new RandomAccessFile(localFile,"r");

OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"),"iso-8859-1"));

//断点续传

if(remoteSize0){

ftpClient.setRestartOffset(remoteSize);

process = remoteSize /step;

raf.seek(remoteSize);

localreadbytes = remoteSize;

}

byte[] bytes = new byte[1024];

int c;

while((c = raf.read(bytes))!= -1){

out.write(bytes,0,c);

localreadbytes+=c;

if(localreadbytes / step != process){

process = localreadbytes / step;

System.out.println("上传进度:" + process);

//TODO 汇报上传状态

}

}

out.flush();

raf.close();

out.close();

boolean result =ftpClient.completePendingCommand();

if(remoteSize  0){

status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;

}else {

status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;

}

return status;

}

public static void main(String[] args) {

ContinueFTP myFtp = new ContinueFTP();

try {

System.err.println(my("10.10.6.236", 21, "5", "jieyan"));

// my(new String("歌曲".getBytes("GBK"),"iso-8859-1"));

// my(new String("歌曲".getBytes("GBK"),"iso-8859-1"));

// my(new String("爱你等于爱自己".getBytes("GBK"),"iso-8859-1"));

// System.out.println(my("E:\yw.flv", "/yw.flv",5));

// System.out.println(my("E:\爱你等于爱自己.mp4","/爱你等于爱自己.mp4"));

//System.out.println(my("/爱你等于爱自己.mp4", "E:\爱你等于爱自己.mp4"));

my;

} catch (IOException e) {

System.out.println("连接FTP出错:"+e.getMessage());

}

}

}

如何在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) {;} } }

java中怎么实现ftp文件传输

package com.quantongfu.;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.net.ServerSocket;

import java.util.List;

import org.apache.commons.net.;

import org.apache.log4j.Logger;

import org.apache.log4j.net.SocketServer;

import com.quantongfu.conf.FtpConf;

/**

 * @项目名称: telinSyslog

 * @文件名称: 

 * @创建日期:2015年9月14日 下午3:22:08

 * @功能描述:ftp实体类,用于连接,上传

 * @修订记录:

 */

public class Ftp {

    private static Logger logger = Logger.getLogger();

    private FTPClient ftp;

    /**

     * 

     * @param path

     *            上传到ftp服务器哪个路径下

     * @param addr

     *            地址

     * @param port

     *            端口号

     * @param username

     *            用户名

     * @param password

     *            密码

     * @return

     * @throws Exception

     */

    public boolean connect() throws Exception {

        boolean result = false;

        ftp = new FTPClient();

        int reply;

        (FtpConf.FTP_HOST, FtpConf.FTP_PORT);

        (FtpConf.FTP_USER_NAME, FtpConf.FTP_PASSWORD);

        ;

        ;

        reply = ;

        if (!FTPReply.isPositiveCompletion(reply)) {

            ;

            return result;

        }

        if (FtpConf.IS_FTP_DIRECTORY) {

            ;

        }

        result = true;

        return result;

    }

    /**

     * 

     * @param files

     *            上传的文件

     * @throws Exception

     */

    public boolean upload(File file) throws IOException {

        FileInputStream input = null;

        try {

            input = new FileInputStream(file);

            boolean b = (file.getName() + ".tmp", input);

            if (b) {

                b = (file.getName() + ".tmp", file.getName());

            }

            return b;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        } finally {

            if (input != null) {

                input.close();

            }

        }

    }

    /**

     * 

     * @param files

     *            上传的文件

     * @throws Exception

     */

    public boolean upload(ServerSocket server, File file) throws Exception {

        FileInputStream input = null;

        try {

            if (!file.exists()) {

                return true;

            }

            input = new FileInputStream(file);

            boolean b = (server, file.getName() + ".tmp", input);

            if (b) {

                b = (file.getName() + ".tmp", file.getName());

                if (b) {

                    file.delete();

                }

            }

            return b;

        } catch (Exception e) {

            logger.error("ftp error" + e.getMessage());

            return false;

        } finally {

            if (input != null) {

                try {

                    input.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

        /*断开连接*/

    public void disConnect() {

        try {

            if (ftp != null) {

                ;

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

        /*获取连接*/

    public static Ftp getFtp() {

        Ftp ftp = new Ftp();

        try {

            ;

        } catch (Exception e) {

            logger.error("FTP连接异常" + e.getMessage());

            e.printStackTrace();

        }

        return ftp;

    }

        /*重连*/

    public Ftp reconnect() {

        disConnect();

        return getFtp();

    }

}

使用Apache FtpClient jar包,获取jar :

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。