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

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

package comweixinutil;
import javaioFile;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javaioOutputStream;
import javaioPrintWriter;
import javaioRandomAccessFile;
import orgapachecommonsnetPrintCommandListener;
import orgapachecommonsnetftpFTP;
import orgapachecommonsnetftpFTPClient;
import orgapachecommonsnetftpFTPFile;
import orgapachecommonsnetftpFTPReply;
import comweixinconstantDownloadStatus;
import comweixinconstantUploadStatus;
/
  支持断点续传的FTP实用类
  @version 01 实现基本断点上传下载
  @version 02 实现上传下载进度汇报
  @version 03 实现中文目录创建及中文文件创建,添加对于中文的支持
 /
public class ContinueFTP {
public FTPClient ftpClient = new FTPClient();

public ContinueFTP(){
//设置将过程中使用到的命令输出到控制台
thisftpClientaddProtocolCommandListener(new PrintCommandListener(new PrintWriter(Systemout)));
}

/
  连接到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{
ftpClientconnect(hostname, port);
ftpClientsetControlEncoding("GBK");
if(FTPReplyisPositiveCompletion(ftpClientgetReplyCode())){
if(ftpClientlogin(username, password)){
return true;
}
}
disconnect();
return false;
}

/
  从FTP服务器上下载文件,支持断点续传,上传百分比汇报
  @param remote 远程文件路径
  @param local 本地文件路径
  @return 上传的状态
  @throws IOException
 /
public DownloadStatus download(String remote,String local) throws IOException{
//设置被动模式
ftpCliententerLocalPassiveMode();
//设置以二进制方式传输
ftpClientsetFileType(FTPBINARY_FILE_TYPE);
DownloadStatus result;

//检查远程文件是否存在
FTPFile[] files = ftpClientlistFiles(new String(remotegetBytes("GBK"),"iso-8859-1"));
if(fileslength != 1){
Systemoutprintln("远程文件不存在");
return DownloadStatusRemote_File_Noexist;
}

long lRemoteSize = files[0]getSize();
File f = new File(local);
//本地存在文件,进行断点下载
if(fexists()){
long localSize = flength();
//判断本地文件大小是否大于远程文件大小
if(localSize >= lRemoteSize){
Systemoutprintln("本地文件大于远程文件,下载中止");
return DownloadStatusLocal_Bigger_Remote;
}

//进行断点续传,并记录状态
FileOutputStream out = new FileOutputStream(f,true);
ftpClientsetRestartOffset(localSize);
InputStream in = ftpClientretrieveFileStream(new String(remotegetBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=localSize /step;
int c;
while((c = inread(bytes))!= -1){
outwrite(bytes,0,c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
Systemoutprintln("下载进度:"+process);
//TODO 更新文件下载进度,值存放在process变量中
}
}
inclose();
outclose();
boolean isDo = ftpClientcompletePendingCommand();
if(isDo){
result = DownloadStatusDownload_From_Break_Success;
}else {
result = DownloadStatusDownload_From_Break_Failed;
}
}else {
OutputStream out = new FileOutputStream(f);
InputStream in= ftpClientretrieveFileStream(new String(remotegetBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=0;
long localSize = 0L;
int c;
while((c = inread(bytes))!= -1){
outwrite(bytes, 0, c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
Systemoutprintln("下载进度:"+process);
//TODO 更新文件下载进度,值存放在process变量中
}
}
inclose();
outclose();
boolean upNewStatus = ftpClientcompletePendingCommand();
if(upNewStatus){
result = DownloadStatusDownload_New_Success;
}else {
result = DownloadStatusDownload_New_Failed;
}
}
return result;
}

/
  上传文件到FTP服务器,支持断点续传
  @param local 本地文件名称,绝对路径
  @param remote 远程文件路径,使用/home/directory1/subdirectory/fileext 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
  @return 上传结果
  @throws IOException
 /
public UploadStatus upload(String local,String remote) throws IOException{
//设置PassiveMode传输
ftpCliententerLocalPassiveMode();
//设置以二进制流的方式传输
ftpClientsetFileType(FTPBINARY_FILE_TYPE);
ftpClientsetControlEncoding("GBK");
UploadStatus result;
//对远程目录的处理
String remoteFileName = remote;
if(remotecontains("/")){
remoteFileName = remotesubstring(remotelastIndexOf("/")+1);
//创建服务器远程目录结构,创建失败直接返回
if(CreateDirecroty(remote, ftpClient)==UploadStatusCreate_Directory_Fail){
return UploadStatusCreate_Directory_Fail;
}
}

//检查远程是否存在文件
FTPFile[] files = ftpClientlistFiles(new String(remoteFileNamegetBytes("GBK"),"iso-8859-1"));
if(fileslength == 1){
long remoteSize = files[0]getSize();
File f = new File(local);
long localSize = flength();
if(remoteSize==localSize){
return UploadStatusFile_Exits;
}else if(remoteSize > localSize){
return UploadStatusRemote_Bigger_Local;
}

//尝试移动文件内读取指针,实现断点续传
result = uploadFile(remoteFileName, f, ftpClient, remoteSize);

//如果断点续传没有成功,则删除服务器上文件,重新上传
if(result == UploadStatusUpload_From_Break_Failed){
if(!ftpClientdeleteFile(remoteFileName)){
return UploadStatusDelete_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(ftpClientisConnected()){
ftpClientdisconnect();
}
}

/
  递归创建远程服务器目录
  @param remote 远程服务器文件绝对路径
  @param ftpClient FTPClient对象
  @return 目录创建是否成功
  @throws IOException
 /
public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{
UploadStatus status = UploadStatusCreate_Directory_Success;
String directory = remotesubstring(0,remotelastIndexOf("/")+1);
if(!directoryequalsIgnoreCase("/")&&!ftpClientchangeWorkingDirectory(new String(directorygetBytes("GBK"),"iso-8859-1"))){
//如果远程目录不存在,则递归创建远程服务器目录
int start=0;
int end = 0;
if(directorystartsWith("/")){
start = 1;
}else{
start = 0;
}
end = directoryindexOf("/",start);
while(true){
String subDirectory = new String(remotesubstring(start,end)getBytes("GBK"),"iso-8859-1");
if(!ftpClientchangeWorkingDirectory(subDirectory)){
if(ftpClientmakeDirectory(subDirectory)){
ftpClientchangeWorkingDirectory(subDirectory);
}else {
Systemoutprintln("创建目录失败");
return UploadStatusCreate_Directory_Fail;
}
}

start = end + 1;
end = directoryindexOf("/",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 = localFilelength() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile,"r");
OutputStream out = ftpClientappendFileStream(new String(remoteFilegetBytes("GBK"),"iso-8859-1"));
//断点续传
if(remoteSize>0){
ftpClientsetRestartOffset(remoteSize);
process = remoteSize /step;
rafseek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while((c = rafread(bytes))!= -1){
outwrite(bytes,0,c);
localreadbytes+=c;
if(localreadbytes / step != process){
process = localreadbytes / step;
Systemoutprintln("上传进度:" + process);
//TODO 汇报上传状态
}
}
outflush();
rafclose();
outclose();
boolean result =ftpClientcompletePendingCommand();
if(remoteSize > 0){
status = resultUploadStatusUpload_From_Break_Success:UploadStatusUpload_From_Break_Failed;
}else {
status = resultUploadStatusUpload_New_File_Success:UploadStatusUpload_New_File_Failed;
}
return status;
}

public static void main(String[] args) {
ContinueFTP myFtp = new ContinueFTP();
try {
Systemerrprintln(myFtpconnect("10106236", 21, "5", "jieyan"));
// myFtpftpClientmakeDirectory(new String("歌曲"getBytes("GBK"),"iso-8859-1"));
// myFtpftpClientchangeWorkingDirectory(new String("歌曲"getBytes("GBK"),"iso-8859-1"));
// myFtpftpClientmakeDirectory(new String("爱你等于爱自己"getBytes("GBK"),"iso-8859-1"));
// Systemoutprintln(myFtpupload("E:\\ywflv", "/ywflv",5));
// Systemoutprintln(myFtpupload("E:\\爱你等于爱自己mp4","/爱你等于爱自己mp4"));
//Systemoutprintln(myFtpdownload("/爱你等于爱自己mp4", "E:\\爱你等于爱自己mp4"));
myFtpdisconnect();
} catch (IOException e) {
Systemoutprintln("连接FTP出错:"+egetMessage());
}
}
}

小鸟云服务器niaoyun实例创建好之后,您可以使用以下任意一种方式登录服务器:
远程桌面连接(MicrosoftTerminalServicesClient,MSTSC):采用这种方式登录,请确保实例能访问公网。如果在创建实例时没有购买带宽,则不能使用远程桌面连接。
管理终端VNC:无论您在创建实例时是否购买了带宽,只要您本地有网页浏览器,都可以通过管理控制台的管理终端登录实例。
使用远程桌面连接(MSTSC)登录实例
打开开始菜单>远程桌面连接,或在开始菜单>搜索中输入mstsc。也可以使用快捷键Win+R来启动运行窗口,输入mstsc后回车启动远程桌面连接。
在远程桌面连接对话框中,输入实例的公网IP地址。单击显示选项。
输入用户名,如小鸟云默认为niaoyun。单击允许我保存凭据,然后单击连接。这样以后登录就不需要手动输入密码了。

前段时间做了一个文件上传ftp功能,你参照一下
package comftpupload;
import javaioFile;
import javaioFileInputStream;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javaioOutputStream;
import orgapachecommonsioFileUtils;
import orgapachecommonsioIOUtils;
import orgapachecommonsnetftpFTPClient;
import orgapachecommonsnetftpFTPFile;
import orgapachecommonsnetftpFTPReply;
public class FTPUpload {
private FTPClient ftpClient = null;

private OutputStream outSteam = null;

/
ftp服务器地址
/
private String hostname = "19216812";
/
ftp服务器端口
/
int port = 21;
/
登录名
/
private String username = "admin";

/
登录密码
/
private String password = "admin";

/
需要访问的远程目录
/
private String remoteDir = "/home/demo";

public FTPUpload() { }

public FTPUpload(String hostname, int port, String username, String password, String remoteDir){
thishostname = hostname;
thisport = port;
thisusername = username;
thispassword = password;
thisremoteDir = remoteDir;

}
/
连接FTP服务器 并登录
@param hostName FTP服务器hostname
@param port FTP服务器端口
@param username FTP登录账号
@param password FTP登录密码
/
private FTPClient connectFTPServer() {
try {
//1创建FTPClient对象
ftpClient = new FTPClient();
//2连接FTP服务器
// 如果采用默认端口,可以使用ftpconnect(url)的方式直接连接FTP服务器
ftpClientconnect(hostname, port); //链接到ftp服务器
// Systemoutprintln("连接到ftp服务器地址 --> ftp://" + hostName + ":" + port + " 成功开始登录");

//3判断连接ftp服务器是否成功
int reply = ftpClientgetReplyCode();
// Systemoutprintln("以2开头的返回值就会为真:" + reply);
//以2开头的返回值就会为真
if (!FTPReplyisPositiveCompletion(reply)) {
ftpClientdisconnect();
return null;
}

//4登录FTP服务器用户名 密码
ftpClientlogin(username, password);
Systemoutprintln("登录成功" );

return ftpClient;
} catch (Exception e) {
eprintStackTrace();
ftpClient = null;
return ftpClient;
}
}

/
向FTP服务器上传文件
@param filePathName 上传文件的全路径名称
@return 成功返回true,否则返回false
/
public boolean uploadFile(String filePathName) {
// 初始表示上传失败
boolean success = false;
try {
// 创建FTPClient对象
ftpClient = connectFTPServer();
//创建文件夹
boolean flag = ftpClientmakeDirectory(remoteDir);
if(flag) {
Systemoutprintln("创建文件夹:" + remoteDir );
}

// 转到指定上传目录
boolean flag0 = ftpClientchangeWorkingDirectory(remoteDir);
// 将上传文件存储到指定目录
if(filePathName == null || filePathNamelength() == 0){
return success;
}
String filename = filePathNamesubstring(filePathNamereplace("\\", "/")lastIndexOf("/") + 1, filePathNamelength());

InputStream input = new FileInputStream(new File(filePathName));

// ftpClientsetBufferSize(1024);
// ftpClientsetControlEncoding("GBK");
// ftpClientsetFileType(FTPClientBINARY_FILE_TYPE);//设置文件类型

boolean flag1 = ftpClientstoreFile(filename, input);
Systemoutprintln("转到指定上传目录:" + flag0 + " 将上传文件存储到指定目录:" + flag1);

inputclose(); // 关闭输入流
ftpClientlogout(); // 退出ftp
success = true; // 表示上传成功

} catch (Exception e) {
eprintStackTrace();
} finally {
if (ftpClientisConnected()) {
try {
ftpClientdisconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/
从FTP服务器指定目录下载文件 到本地目录中 OK
@param fileName 要下载的文件名
@param localPath 下载后保存到本地的路径
@param showlist 下载时是否显示列表 ( true 显示 )
@return
/
public boolean downFile(String fileName, String localPath, boolean showlist) {
// 初始表示下载失败
boolean success = false;
if(fileName == null || fileNamelength() == 0 || localPath == null || localPathlength() == 0){
return success;
}
try {
File file = new File(localPath);

if(!fileisDirectory()){
filemkdir();
}
// 创建FTPClient对象
ftpClient = connectFTPServer();
// 转到指定下载目录
boolean flag = ftpClientchangeWorkingDirectory(remoteDir);
if(!flag) {
Systemoutprintln("目录:" + remoteDir +"不存在!");
return success;
}
// 列出该目录下所有文件
FTPFile[] remoteFiles = ftpClientlistFiles();
// 遍历所有文件,找到指定的文件
if(showlist){
Systemoutprintln("目录" + remoteDir + "下的文件:");
}

for (FTPFile ftpFile : remoteFiles) {
String name = ftpFilegetName();
if(showlist){
long length = ftpFilegetSize();
String readableLength = FileUtilsbyteCountToDisplaySize(length);
Systemoutprintln(name + ":\t\t" + readableLength);
}

if (nameequals(fileName)) {
// 根据绝对路径初始化文件
File localFile = new File(localPath + "/" + name);
// 输出流
OutputStream is = new FileOutputStream(localFile);
// 下载文件
ftpClientretrieveFile(name, is);
isclose();
}
}
// 退出ftp
ftpClientlogout();
// 下载成功
success = true;
} catch (IOException e) {
eprintStackTrace();
} finally {
if (ftpClientisConnected()) {
try {
ftpClientdisconnect();
} catch (IOException ioe) {
}
}
}
return success;
}

/
显示FTP服务器指定文件夹中的文件及大小 OK
@return
/
private boolean showFileList() {
// 初始表示失败
boolean success = false;
try {
ftpClient = connectFTPServer();
FTPFile[] remoteFiles = null;
// 转到指定下载目录
boolean flag = ftpClientchangeWorkingDirectory(remoteDir);
if(!flag) {
Systemoutprintln("目录:" + remoteDir +"不存在!");
return success;
} else{
remoteFiles = ftpClientlistFiles(remoteDir);
Systemoutprintln("目录" + remoteDir + "下的文件:");
}

if(remoteFiles != null) {
for(int i=0;i < remoteFileslength; i++){
String name = remoteFiles[i]getName();
long length = remoteFiles[i]getSize();
String readableLength = FileUtilsbyteCountToDisplaySize(length);
Systemoutprintln(name + ":\t\t" + readableLength);
}
}
// 表示成功
success = true;
} catch (Exception e) {
eprintStackTrace();
} finally {
//使用IO包关闭流
IOUtilscloseQuietly(outSteam);
try {
ftpClientdisconnect();
} catch (IOException ioe) {
ioeprintStackTrace();
}
}
return success;
}
public static void main(String[] args) {
FTPUpload ftp = new FTPUpload();
ftpuploadFile("c:////test////bgsspjar");
}
}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zz/12707637.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2025-08-27
下一篇2025-08-27

发表评论

登录后才能评论

评论列表(0条)

    保存