導航:首頁 > 編程語言 > java用ftp做數據傳輸方案

java用ftp做數據傳輸方案

發布時間:2024-04-30 13:32:38

⑴ 我想登錄一個ftp然後把某個目錄的所有文件考到另一個ftp的目錄的某個文件夾下用java代碼實現

用的commons-net包中的FTPClient
ftp1為拷貝目錄,ftp2為被拷貝目錄
你先登錄ftp2調用ftp1,
ftpClient1.changeWorkingDirectory(path);
InputStream inputStream = ftpClient1.retrieveFileStream(file.getName());
用這個代碼應該可以從ftp1中獲得一個inputStream ,在ftp2中可以做上傳操作
目錄的話ftp2還要做遞歸存放到list中,ftp2遍歷上傳. 其實我也沒做這個,希望思路有點幫助,應該可以實現.good luck!~~~

⑵ JAVA 傳輸文件

//以前寫的一個文件傳輸的小程序,有客戶端和伺服器端兩部分,伺服器可//以一直運行,客戶端傳輸完一個後退出,當然你也可以根據你的需要改。
//伺服器端可以支持多個客戶端同時上傳,用到了多線程
/**
* 文件傳輸,客戶端
* @aurth anyx
*/
//package per.anyx.ftp;

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

public class FtpClient{
public static void main(String[] args){
if(args.length != 3){
System.out.println("Usage: FtpClient host_add host_port src_file");
System.exit(0);
}
File file = new File(args[2]);
if(!file.exists() || !file.isFile()){
System.out.println("File \"" + args[2] + "\" does not exist or is not a normal file.");
System.exit(0);
}
Socket s = null;
FileInputStream in = null;
OutputStream out = null;
try{
s = new Socket(args[0], Integer.parseInt(args[1]));
in = new FileInputStream(file);
out = s.getOutputStream();

byte[] buffer = new byte[1024*8];
int len = -1;
System.out.println("File tansfer statr...");
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
System.out.println("File tansfer complete...");
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
System.exit(1);
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
}catch(Exception e){}
}
}
}

/**
* 文件傳輸,伺服器端
* @aurth anyx
*/
//package per.anyx.ftp;

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

public class FtpServer{
public static void main(String[] args){
if(args.length != 1){
System.out.println("Usage: FtpServer server_port");
System.exit(0);
}
ServerSocket ss = null;
try{
ss = new ServerSocket(Integer.parseInt(args[0]));
System.out.println("FtpServer start on port ..." + args[0]);
while(true){
Socket s = ss.accept();
new FtpThread(s).start();
System.out.println(s.getInetAddress().getHostAddress() + " connected.");
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}finally{
try{
if(ss != null) ss.close();
}catch(Exception e){}
}
}
}

class FtpThread extends Thread{
Socket s;
long fileName = 0;
public FtpThread(Socket s){
this.s = s;
}
public void run(){
FileOutputStream out = null;
InputStream in = null;
File file = null;
do{
file = new File("" + (fileName++));
}while(file.exists());
try{
out = new FileOutputStream(file);
in = s.getInputStream();

byte[] buffer = new byte[1024*8];
int len = -1;
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
System.out.println(s.getInetAddress().getHostAddress() + " connect closed..");
}catch(Exception e){}
}
}
}

⑶ javaweb 怎麼樣將本地文件傳輸到遠程伺服器

可以通過JDK自帶的API實現,如下代碼:
package com.cloudpower.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* Java自帶的API對FTP的操作
* @Title:Ftp.java
*/
public class Ftp {
/**
* 本地文件名
*/
private String localfilename;
/**
* 遠程文件名
*/
private String remotefilename;
/**
* FTP客戶端
*/
private FtpClient ftpClient;

/**
* 伺服器連接
* @param ip 伺服器IP
* @param port 伺服器埠
* @param user 用戶名
* @param password 密碼
* @param path 伺服器路徑
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******連接伺服器的兩種方法*******/
//第一種方法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二種方法
ftpClient = new FtpClient(ip);

ftpClient.login(user, password);
// 設置成2進制傳輸
ftpClient.binary();
System.out.println("login success!");
if (path.length() != 0){
//把遠程系統上的目錄切換到參數path所指定的目錄
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println("disconnect success");
} catch (IOException ex) {
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void upload(String localFile, String remoteFile) {
this.localfilename = localFile;
this.remotefilename = remoteFile;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//將遠程文件加入輸出流中
os = ftpClient.put(this.remotefilename);
//獲取本地文件的輸入流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//創建一個緩沖區
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("upload success");
} catch (IOException ex) {
System.out.println("not upload");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
is = ftpClient.get(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("download success");
} catch (IOException ex) {
System.out.println("not download");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String agrs[]) {

String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};

Ftp fu = new Ftp();
/*
* 使用默認的埠號、用戶名、密碼以及根目錄連接FTP伺服器
*/
fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");

//下載
for (int i = 0; i < filepath.length; i++) {
fu.download(filepath[i], localfilepath[i]);
}

String localfile = "E:\\號碼.txt";
String remotefile = "/temp/哈哈.txt";
//上傳
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}

⑷ 如何使用java遠程傳輸文件,client只提供ip\文件路徑等參數,server端無需部署服務!

其實有幾種方式的,
1 ftp傳輸應用情況,加入在linux系統端有一些文件需要下載到用戶電腦專client端,而linux系統又不是web伺服器,屬那麼可以通過java程序FTP方式登錄到linux,讀取文件轉換為流輸出到用戶IE端, java訪問Linux伺服器讀取文件 所需jar包:j2ssh-core-0.2.2.jar
2 socket方式,可以應用於比如server-client 聊天窗,傳輸文字;
3 http協議,這種就是最常用的了,比如打開IE下載,上傳東西,java是通過jsp servlet來實現的,然後部署放在tomcat web 伺服器上,在其他區域網環境下的電腦登錄IE即可訪問到。沒有特殊jar,只用java servlet的jar即可。例子如附件,可能上傳不成功哈,網路網路會有很多哈

⑸ java 實現ftp上傳如何創建文件夾

這個功能我也剛寫完,不過我也是得益於同行,現在我也把自己的分享給大家,希望能對大家有所幫助,因為自己的項目不涉及到創建文件夾,也僅作分享,不喜勿噴謝謝!

interface:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;

publicinterfaceIFtpUtils{
/**
*ftp登錄
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@paramfpathftp路徑
*@paramlocalpath本地路徑
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下載文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*關閉流連接、ftp連接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}

impl:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;

{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;

@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//設置文件類型為二進制(避免解壓縮文件失敗)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//開通數據埠傳輸數據,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("連接FTP失敗,用戶名或密碼錯誤");
}else{
log.info("FTP連接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登錄FTP失敗,請檢查FTP相關配置信息是否正確",e1);
}
}
}
returnftpClient;
}

@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上傳失敗");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上傳成功");
}
returnfalse;
}

@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切換到當前目錄
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;

}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下載成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}

@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夾是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,請檢查。。。");
}
}
}
}
}


@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}


publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下載/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}

⑹ 如何在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做數據傳輸方案相關的資料

熱點內容
大數據線下測試 瀏覽:147
一汽大眾手機互聯app叫什麼 瀏覽:984
大千世界在哪個文件夾 瀏覽:610
cfwpe封包抓取教程 瀏覽:897
哈利波特版本 瀏覽:663
如何從多行列中返回第一列數據 瀏覽:579
一個t的文件能有多少照片 瀏覽:174
安卓qq文件在哪個文件夾里 瀏覽:729
放圖片的文件夾什麼格式 瀏覽:213
win10esp精簡版 瀏覽:865
文件名1688quick 瀏覽:927
del文件是哪個資料庫的 瀏覽:901
java將字元串轉換為整型 瀏覽:175
win7批量修改部分文件名 瀏覽:873
win8需要升級到win10么 瀏覽:85
大數據在海關的運用 瀏覽:38
android使用javamail 瀏覽:3
win10快速訪問共享文件 瀏覽:259
喜馬拉雅電腦文件導出 瀏覽:615
js取商運算 瀏覽:719

友情鏈接