當前位置:首頁 » 文件傳輸 » 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的下載地址貼出來