当前位置:首页 » 文件传输 » ftp下载文件Java代码咋写
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

ftp下载文件Java代码咋写

发布时间: 2023-08-27 19:22:32

❶ java获取ftp文件路径怎么写

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.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

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(FTP.BINARY_FILE_TYPE);
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(FTP.BINARY_FILE_TYPE);
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(remoteSize>0){
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(myFtp.connect("10.10.6.236", 21, "5", "jieyan"));
// myFtp.ftpClient.makeDirectory(new String("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(new String("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(new String("爱你等于爱自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\\yw.flv", "/yw.flv",5));
// System.out.println(myFtp.upload("E:\\爱你等于爱自己.mp4","/爱你等于爱自己.mp4"));
//System.out.println(myFtp.download("/爱你等于爱自己.mp4", "E:\\爱你等于爱自己.mp4"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println("连接FTP出错:"+e.getMessage());
}
}
}

❷ java怎么在ftp上取到文件夹中文件再录入txt文本

前段时间正好看了这个。

http://www.codejava.net/java-se/networking/ftp/java-ftp-file-download-tutorial-and-example

这个文档非常好。有什么看不懂的再问吧。

主要是使用org.apache.commons.net.ftp.FTPClient 和org.apache.commons.net.ftp.FTP 类。

核心代码:

ftpClient.connect(server,port);
ftpClient.login(user,pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

//APPROACH#1:usingretrieveFile(String,OutputStream)
StringremoteFile1="/test/video.mp4";
FiledownloadFile1=newFile("D:/Downloads/video.mp4");
OutputStreamoutputStream1=newBufferedOutputStream(newFileOutputStream(downloadFile1));
booleansuccess=ftpClient.retrieveFile(remoteFile1,outputStream1);
outputStream1.close();

if(success){
System.out.println("File#.");
}

❸ java如何实现txt下载 就是从远程FTP服务器上直接把TXT文本下载下来!

strUrl为文件地址,fileName为文件在本地的保存路径,试试吧~

public static void writeFile(String strUrl, String fileName) {
URL url = null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream os = null;
try {
os = new FileOutputStream( fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];

while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
System.out.println("下载成功:"+strUrl);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

❹ 求用java写一个ftp服务器客户端程序。

import java.io.*;
import java.net.*;public class ftpServer extends Thread{ public static void main(String args[]){
String initDir;
initDir = "D:/Ftp";
ServerSocket server;
Socket socket;
String s;
String user;
String password;
user = "root";
password = "123456";
try{
System.out.println("MYFTP服务器启动....");
System.out.println("正在等待连接....");
//监听21号端口
server = new ServerSocket(21);
socket = server.accept();
System.out.println("连接成功");
System.out.println("**********************************");
System.out.println("");

InputStream in =socket.getInputStream();
OutputStream out = socket.getOutputStream();

DataInputStream din = new DataInputStream(in);
DataOutputStream dout=new DataOutputStream(out);
System.out.println("请等待验证客户信息....");

while(true){
s = din.readUTF();
if(s.trim().equals("LOGIN "+user)){
s = "请输入密码:";
dout.writeUTF(s);
s = din.readUTF();
if(s.trim().equals(password)){
s = "连接成功。";
dout.writeUTF(s);
break;
}
else{s ="密码错误,请重新输入用户名:";<br> dout.writeUTF(s);<br> <br> }
}
else{
s = "您输入的命令不正确或此用户不存在,请重新输入:";
dout.writeUTF(s);
}
}
System.out.println("验证客户信息完毕...."); while(true){
System.out.println("");
System.out.println("");
s = din.readUTF();
if(s.trim().equals("DIR")){
String output = "";
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
for(int i=0;i<dirStructure.length;i++){
output +=dirStructure[i]+"\n";
}
s=output;
dout.writeUTF(s);
}
else if(s.startsWith("GET")){
s = s.substring(3);
s = s.trim();
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
String e= s;
int i=0;
s ="不存在";
while(true){
if(e.equals(dirStructure[i])){
s="存在";
dout.writeUTF(s);
RandomAccessFile outFile = new RandomAccessFile(initDir+"/"+e,"r");
byte byteBuffer[]= new byte[1024];
int amount;
while((amount = outFile.read(byteBuffer)) != -1){
dout.write(byteBuffer, 0, amount);break;
}break;

}
else if(i<dirStructure.length-1){
i++;
}
else{
dout.writeUTF(s);
break;
}
}
}
else if(s.startsWith("PUT")){
s = s.substring(3);
s = s.trim();
RandomAccessFile inFile = new RandomAccessFile(initDir+"/"+s,"rw");
byte byteBuffer[] = new byte[1024];
int amount;
while((amount =din.read(byteBuffer) )!= -1){
inFile.write(byteBuffer, 0, amount);break;
}
}
else if(s.trim().equals("BYE"))break;
else{
s = "您输入的命令不正确或此用户不存在,请重新输入:";
dout.writeUTF(s);
}
}

din.close();
dout.close();
in.close();
out.close();
socket.close();
}
catch(Exception e){
System.out.println("MYFTP关闭!"+e);

}
}}

❺ FTP客户端程序设计(java)

package jing.upfile;

import sun.net.ftp.*;
import sun.net.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
FTP远程命令列表<br>
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>
* <p>Title: 使用JAVA操作FTP服务器(FTP客户端)</p>
* <p>Description: 上传文件的类型及文件大小都放到调用此类的方法中去检测,比如放到前台JAVASCRIPT中去检测等
* 针对FTP中的所有调用使用到文件名的地方请使用完整的路径名(绝对路径开始)。
* </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: 静靖工作室</p>
* @author 欧朝敬 13873195792
* @version 1.0
*/

public class FtpUpfile {
private FtpClient ftpclient;
private String ipAddress;
private int ipPort;
private String userName;
private String PassWord;
/**
* 构造函数
* @param ip String 机器IP
* @param port String 机器FTP端口号
* @param username String FTP用户名
* @param password String FTP密码
* @throws Exception
*/
public FtpUpfile(String ip, int port, String username, String password) throws
Exception {
ipAddress = new String(ip);
ipPort = port;
ftpclient = new FtpClient(ipAddress, ipPort);
//ftpclient = new FtpClient(ipAddress);
userName = new String(username);
PassWord = new String(password);
}

/**
* 构造函数
* @param ip String 机器IP,默认端口为21
* @param username String FTP用户名
* @param password String FTP密码
* @throws Exception
*/
public FtpUpfile(String ip, String username, String password) throws
Exception {
ipAddress = new String(ip);
ipPort = 21;
ftpclient = new FtpClient(ipAddress, ipPort);
//ftpclient = new FtpClient(ipAddress);
userName = new String(username);
PassWord = new String(password);
}

/**
* 登录FTP服务器
* @throws Exception
*/
public void login() throws Exception {
ftpclient.login(userName, PassWord);
}

/**
* 退出FTP服务器
* @throws Exception
*/
public void logout() throws Exception {
//用ftpclient.closeServer()断开FTP出错时用下更语句退出
ftpclient.sendServer("QUIT\r\n");
int reply = ftpclient.readServerResponse(); //取得服务器的返回信息
}

/**
* 在FTP服务器上建立指定的目录,当目录已经存在的情下不会影响目录下的文件,这样用以判断FTP
* 上传文件时保证目录的存在目录格式必须以"/"根目录开头
* @param pathList String
* @throws Exception
*/
public void buildList(String pathList) throws Exception {
ftpclient.ascii();
StringTokenizer s = new StringTokenizer(pathList, "/"); //sign
int count = s.countTokens();
String pathName = "";
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpclient.sendServer("XMKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
}
int reply = ftpclient.readServerResponse();
}
ftpclient.binary();
}

/**
* 取得指定目录下的所有文件名,不包括目录名称
* 分析nameList得到的输入流中的数,得到指定目录下的所有文件名
* @param fullPath String
* @return ArrayList
* @throws Exception
*/
public ArrayList fileNames(String fullPath) throws Exception {
ftpclient.ascii(); //注意,使用字符模式
TelnetInputStream list = ftpclient.nameList(fullPath);
byte[] names = new byte[2048];
int bufsize = 0;
bufsize = list.read(names, 0, names.length); //从流中读取
list.close();
ArrayList namesList = new ArrayList();
int i = 0;
int j = 0;
while (i < bufsize /*names.length*/) {
//char bc = (char) names;
//System.out.println(i + " " + bc + " : " + (int) names);
//i = i + 1;
if (names == 10) { //字符模式为10,二进制模式为13
//文件名在数据中开始下标为j,i-j为文件名的长度,文件名在数据中的结束下标为i-1
//System.out.write(names, j, i - j);
//System.out.println(j + " " + i + " " + (i - j));
String tempName = new String(names, j, i - j);
namesList.add(tempName);
//System.out.println(temp);
// 处理代码处
//j = i + 2; //上一次位置二进制模式
j = i + 1; //上一次位置字符模式
}
i = i + 1;
}
return namesList;
}

/**
* 上传文件到FTP服务器,destination路径以FTP服务器的"/"开始,带文件名、
* 上传文件只能使用二进制模式,当文件存在时再次上传则会覆盖
* @param source String
* @param destination String
* @throws Exception
*/
public void upFile(String source, String destination) throws Exception {
buildList(destination.substring(0, destination.lastIndexOf("/")));
ftpclient.binary(); //此行代码必须放在buildList之后
TelnetOutputStream ftpOut = ftpclient.put(destination);
TelnetInputStream ftpIn = new TelnetInputStream(new
FileInputStream(source), true);
byte[] buf = new byte[204800];
int bufsize = 0;
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
ftpIn.close();
ftpOut.close();

}

/**
* JSP中的流上传到FTP服务器,
* 上传文件只能使用二进制模式,当文件存在时再次上传则会覆盖
* 字节数组做为文件的输入流,此方法适用于JSP中通过
* request输入流来直接上传文件在RequestUpload类中调用了此方法,
* destination路径以FTP服务器的"/"开始,带文件名
* @param sourceData byte[]
* @param destination String
* @throws Exception
*/
public void upFile(byte[] sourceData, String destination) throws Exception {
buildList(destination.substring(0, destination.lastIndexOf("/")));
ftpclient.binary(); //此行代码必须放在buildList之后
TelnetOutputStream ftpOut = ftpclient.put(destination);
ftpOut.write(sourceData, 0, sourceData.length);
// ftpOut.flush();
ftpOut.close();
}

/**
* 从FTP文件服务器上下载文件SourceFileName,到本地destinationFileName
* 所有的文件名中都要求包括完整的路径名在内
* @param SourceFileName String
* @param destinationFileName String
* @throws Exception
*/
public void downFile(String SourceFileName, String destinationFileName) throws
Exception {
ftpclient.binary(); //一定要使用二进制模式
TelnetInputStream ftpIn = ftpclient.get(SourceFileName);
byte[] buf = new byte[204800];
int bufsize = 0;
FileOutputStream ftpOut = new FileOutputStream(destinationFileName);
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
ftpOut.close();
ftpIn.close();
}

/**
*从FTP文件服务器上下载文件,输出到字节数组中
* @param SourceFileName String
* @return byte[]
* @throws Exception
*/
public byte[] downFile(String SourceFileName) throws
Exception {
ftpclient.binary(); //一定要使用二进制模式
TelnetInputStream ftpIn = ftpclient.get(SourceFileName);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
byte[] buf = new byte[204800];
int bufsize = 0;

while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
byteOut.write(buf, 0, bufsize);
}
byte[] return_arraybyte = byteOut.toByteArray();
byteOut.close();
ftpIn.close();
return return_arraybyte;
}

/**调用示例
* FtpUpfile fUp = new FtpUpfile("192.168.0.1", 21, "admin", "admin");
* fUp.login();
* fUp.buildList("/adfadsg/sfsdfd/cc");
* String destination = "/test.zip";
* fUp.upFile("C:\\Documents and Settings\\Administrator\\My Documents\\sample.zip",destination);
* ArrayList filename = fUp.fileNames("/");
* for (int i = 0; i < filename.size(); i++) {
* System.out.println(filename.get(i).toString());
* }
* fUp.logout();
* @param args String[]
* @throws Exception
*/
public static void main(String[] args) throws Exception {
FtpUpfile fUp = new FtpUpfile("192.150.189.22", 21, "admin", "admin");
fUp.login();
/* fUp.buildList("/adfadsg/sfsdfd/cc");
String destination = "/test/SetupDJ.rar";
fUp.upFile(
"C:\\Documents and Settings\\Administrator\\My Documents\\SetupDJ.rar",
destination);
ArrayList filename = fUp.fileNames("/");
for (int i = 0; i < filename.size(); i++) {
System.out.println(filename.get(i).toString());
}

fUp.downFile("/sample.zip", "d:\\sample.zip");
*/
FileInputStream fin = new FileInputStream(
"C:\\AAA.TXT");
byte[] data = new byte[20480];
fin.read(data, 0, data.length);
fUp.upFile(data, "/test/BBB.exe");
fUp.logout();
System.out.println("程序运行完成!");
/*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删除文件
*/
}
}

❻ 求每日定时在服务器的FTP上取数据文件的源码(JAVA)

这个是可以向服务器端发送文字的程序,就是在客户端发送一句hello在服务器也可以接受到hello,这个程序可以修改一下就可以了。具体修改方法是增加一个定时器,然后把字符流改成字节流,现在有点忙,你先研究啊,近两天帮你写写看。
服务器端:
import java.net.*;
import java.io.*;

public class DateServer {
public static void main(String[] args) {
ServerSocket server=null;

try{
server=new ServerSocket(6666);
System.out.println(
"Server start on port 6666...");
while(true){
Socket socket=server.accept();
new SocketHandler(socket).start();
/*
PrintWriter out=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
out.println(new java.util.Date().toLocaleString());
out.close();
*/
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(server!=null) {
try{
server.close();
}catch(Exception ex){}
}
}
}
}

class SocketHandler extends Thread {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket=socket;
}
public void run() {
try{
PrintWriter out=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
out.println(
new java.util.Date().
toLocaleString());
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
客户端:
package com.briup;

import java.io.*;
import java.net.*;

public class FtpClient {
public static void main(String[] args) {
if(args.length==0) {
System.out.println("Usage:java FtpClient file_path");
System.exit(0);
}
File file=new File(args[0]);
if(!file.exists()||!file.canRead()) {
System.out.println(args[0]+" doesn't exist or can not read.");
System.exit(0);
}

Socket socket=null;

try{
socket=new Socket(args[1],Integer.parseInt(args[2]));
BufferedInputStream in=new BufferedInputStream(
new FileInputStream(file)
);
BufferedOutputStream out=new BufferedOutputStream(
socket.getOutputStream()
);
byte[] buffer=new byte[1024*8];
int i=-1;
while((i=in.read(buffer))!=-1) {
out.write(buffer,0,i);
}
System.out.println(socket.getInetAddress().getHostAddress()+" send file over.");
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}finally{
if(socket!=null) {
try{
socket.close();
}catch(Exception ex){}
}
}
}
}

❼ 怎样用java开发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;
import zn.ccfccb.util.CCFCCBUtil;
import zn.ccfccb.util.ZipUtilAll;

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

// 调用样例:
public static void main(String[] args) {
try {
// 密钥/res/20150228
// ZipUtilAll.unZip(new File(("D:/123/123.zip")), "D:/123/");
// ZipDemo1232.unZip(new File(("D:/123/123.zip")), "D:/123/");
// 明文文件路径
String plainFilePath = "D:/req_20150204_0011.txt";
// 密文文件路径
String secretFilePath = "req_20150204_00134.txt";
// 加密
// encodeAESFile(key, plainFilePath, secretFilePath);
fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
ZipUtilAll.unZip("D://123.zip", "D:/123/李筱/");
// 解密
plainFilePath = "D:/123.sql";
// secretFilePath = "D:/test11111.sql";
// decodeAESFile(key, plainFilePath, secretFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}

}

❽ java FTP下载文件在代码中如何实现知道下载完成

(KmConfigkmConfig,StringfileName,StringclientFileName,OutputStreamoutputStream){
try{
StringftpHost=kmConfig.getFtpHost();
intport=kmConfig.getFtpPort();
StringuserName=kmConfig.getFtpUser();
StringpassWord=kmConfig.getFtpPassword();
Stringpath=kmConfig.getFtpPath();
FtpClientftpClient=newFtpClient(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{
TelnetInputStreamin=ftpClient.get(fileName);
byte[]bytes=newbyte[1024];
intcnt=0;
while((cnt=in.read(bytes,0,bytes.length))!=-1){
outputStream.write(bytes,0,cnt);
}
//##############################################
//这里文件就已经下载完了,自己理解一下
//#############################################

outputStream.close();
in.close();
}catch(Exceptione){
ftpClient.closeServer();
e.printStackTrace();
}
ftpClient.closeServer();
}catch(Exceptione){
System.out.println("下载文件失败!请检查系统FTP设置,并确认FTP服务启动");
}
}

❾ java 下载异地FTP中的zip文件

好像需要一个支持jar包把,把ftp4j的下载地址贴出来