當前位置:首頁 » 文件管理 » javaftpdemo

javaftpdemo

發布時間: 2022-11-14 19:55:05

java ftp怎麼實現java 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伺服器的銜接,運用默許埠號。

❷ 用java編寫ftp客戶端這樣的網路程序需用到Java的什麼知識

會socket編程就可以了
我給你個測試:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import sun.net.ftp.*;

//FTP連接與瀏覽

public class FtpClientDemo extends JFrame{

JTextField jtfServer; //輸入Ftp伺服器地址
JTextField jtfUser; //輸入用戶名
JPasswordField jtfPass; //輸入密碼
JButton jbConnect; //連接按鈕
JButton jbDisconnect; //斷開按鈕
JTextArea jtaShowFiles; //顯示伺服器目錄與文件
FtpClient ftpClient;

public FtpClientDemo(){
super("FTP連接與瀏覽"); //調用父類構造函數

jtfServer=new JTextField(13); //實例化組件
jtfUser=new JTextField(8);
jtfPass=new JPasswordField(8);
jbConnect=new JButton("連接");
jbDisconnect=new JButton("斷開");
jtaShowFiles=new JTextArea();

Container container=getContentPane(); //得到容器
JPanel panel=new JPanel(); //實例化面板
panel.add(new JLabel("地址")); //增加組件到面板上
panel.add(jtfServer);
panel.add(new JLabel("用戶名"));
panel.add(jtfUser);
panel.add(new JLabel("密碼"));
panel.add(jtfPass);
container.add(panel,BorderLayout.NORTH); //增加組件到容器上
JScrollPane jsp=new JScrollPane(jtaShowFiles);
container.add(jsp,BorderLayout.CENTER);
panel=new JPanel();
panel.add(jbConnect);
panel.add(jbDisconnect);
container.add(panel,BorderLayout.SOUTH);

jbConnect.addActionListener(new ActionListener(){ //連接按鈕事件處理
public void actionPerformed(ActionEvent ent){
connectServer(); //調用連接到伺服器的方法
}
});

jbDisconnect.addActionListener(new ActionListener(){ //斷開按鈕事件處理
public void actionPerformed(ActionEvent ent){
disconnectServer(); //調用斷開與伺服器連接的方法
}
});

setSize(460,260); //設置窗口尺寸
setVisible(true); //設置窗口可視
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口時退出程序
}

public void connectServer(){
try{
ftpClient = new FtpClient(); //實例化FtpClient對象
String serverAddr=jtfServer.getText(); //得到伺服器地址
String user=jtfUser.getText(); //得到用戶名
String pass=jtfPass.getPassword().toString(); //得到密碼
ftpClient.openServer(serverAddr); //連接到伺服器
ftpClient.login(user,pass); //在伺服器上注冊
InputStream is=ftpClient.list(); //得到伺服器目錄與文件列表輸入流
StringBuffer info=new StringBuffer(); //實例化StringBuffer對象,用於輸出信息
int ch;
while ((ch=is.read())>=0){ //未讀完列表,則繼續
info.append((char)ch); //增加信息
}
jtaShowFiles.setText(new String(info)); //顯示信息
is.close(); //關閉輸入流
}
catch (IOException ex){
JOptionPane.showMessageDialog(FtpClientDemo.this,ex.getMessage()); //顯示提示信息
ex.printStackTrace(); //在命令行窗口輸出出錯信息
}

}

public void disconnectServer(){
try{
ftpClient.closeServer(); //關閉與伺服器的連接
}
catch (IOException ex){
ex.printStackTrace();
}
}

public static void main(String[] args){
new FtpClientDemo();
}
}

❸ 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訪問

在主函數中,完成伺服器埠的偵聽和服務線程的創建。我們利用一個靜態字元串變數initDir 來保存伺服器線程運行時所在的工作目錄。伺服器的初始工作目錄是由程序運行時用戶輸入的,預設為C盤的根目錄。
具體的代碼如下:
public class ftpServer extends Thread{
private Socket socketClient;
private int counter;
private static String initDir;
public static void main(String[] args){
if(args.length != 0) {
initDir = args[0];
}else{ initDir = "c:";}
int i = 1;
try{
System.out.println("ftp server started!");
//監聽21號埠
ServerSocket s = new ServerSocket(21);
for(;;){
//接受客戶端請求
Socket incoming = s.accept();
//創建服務線程
new ftpServer(incoming,i).start();
i++;
}
}catch(Exception e){}
}

❺ 怎麼用Java實現FTP上傳

sun.net.ftp.FtpClient.,該類庫主要提供了用於建立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.FtpClient;

/**
* 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 + "\r\n");
} 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");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上傳成功!" : "上傳失敗!");
ftp.closeServer();
/**
* 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刪除文件
*/
}
}

❻ java中怎麼實現ftp伺服器

我知道apache有個commons net包,其中的FTPClient類可以實現客戶端和服務之間的文件傳輸,但是我如果使用這種方式的話,就得將一台伺服器上的文件傳到我本地,再將這個文件傳到另一台伺服器上,感覺這中間多了一步操作;

❼ JAVA怎麼實現刪除遠程FTP伺服器上的某一文件

一個JAVA 實現FTP功能的代碼,包括了伺服器的設置模塊,並包括有上傳文件至FTP的通用方法、下載文件的通用方法以及刪除文件、在ftp伺服器上傳文件夾、檢測文件夾是否存在等,裡面的有些代碼對編寫JAVA文件上傳或許有參考價值,

(1):Java FTP主文件代碼:

package ftpDemo;

import java.io.DataOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import sun.net.TelnetInputStream;

import sun.net.TelnetOutputStream;

import sun.net.ftp.FtpClient;

public class ftpUtil {

// 上傳文件至FTP通用方法

public static void upLoadFileFtp(KmConfig kmConfig,InputStream is, String fileName){

try {

String ftpHost = kmConfig.getFtpHost();

int port = kmConfig.getFtpPort();

String userName = kmConfig.getFtpUser();

String passWord = kmConfig.getFtpPassword();

String path = kmConfig.getFtpPath();

FtpClient ftpClient = new FtpClient(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伺服器上保存上傳文件的路徑。

TelnetOutputStream telnetOut = ftpClient.put(fileName);// fileName為上傳的文件名

DataOutputStream dataOut = new DataOutputStream(telnetOut);

byte buffer[] = new byte[ * ];

int count = ;

while ((count = is.read(buffer)) != -) {

dataOut.write(buffer, , count);

}

telnetOut.close();

dataOut.close();

ftpClient.closeServer();

} catch (Exception e) {

System.out.println("上傳文件失敗!請檢查系統FTP設置,並確認FTP服務啟動");

}

}

// 刪除文件至FTP通用方法

public static void deleteFileFtp(KmConfig kmConfig,String fileName){

try {

String ftpHost = kmConfig.getFtpHost();

int port = kmConfig.getFtpPort();

String userName = kmConfig.getFtpUser();

String passWord = kmConfig.getFtpPassword();

String path = kmConfig.getFtpPath();

FtpClient ftpClient = new FtpClient(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 {

ftpClient.sendServer("dele " + fileName + " ");

} catch (Exception e) {

System.out.println("刪除文件失敗!請檢查系統FTP設置,並確認FTP服務啟動");

}

ftpClient.closeServer();

} catch (Exception e) {

System.out.println("刪除文件失敗!");

}

}

// 下載ftp文件

public static void downloadFileFtp(KmConfig kmConfig,String fileName, String clientFileName, OutputStream outputStream){

try {

String ftpHost = kmConfig.getFtpHost();

int port = kmConfig.getFtpPort();

String userName = kmConfig.getFtpUser();

String passWord = kmConfig.getFtpPassword();

String path = kmConfig.getFtpPath();

FtpClient ftpClient = new FtpClient(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 {

TelnetInputStream in = ftpClient.get(fileName);

byte[] bytes = new byte[];

int cnt=;

while ((cnt=in.read(bytes,,bytes.length)) != -) {

outputStream.write(bytes, , cnt);

}

outputStream.close();

in.close();

} catch (Exception e) {

ftpClient.closeServer();

e.printStackTrace();

}

ftpClient.closeServer();

} catch (Exception e) {

System.out.println("下載文件失敗!請檢查系統FTP設置,並確認FTP服務啟動");

}

}

//在ftp伺服器上傳件文件夾

public boolean createDir(String path,FtpClient ftpClient) throws Exception{

//進入到home文件夾下

ftpClient.cd("/home");

//創建遠程文件夾

//遠程命令包括

//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>

//通過遠程命令 穿件一個files文件夾

ftpClient.sendServer("MKD "+ path + " ");

//這個方法必須在 這兩個方法中間調用 否則 命令不管用

ftpClient.binary();

ftpClient.readServerResponse();

return false;

}

/**

* 檢查文件夾是否存在

* @param dir

* @param ftpClient

* @return

*/

public boolean isDirExist(String dir, FtpClient ftpClient) {

try {

ftpClient.cd(dir);

} catch (Exception e) {

return false;

}

return true;

}

}

(2):KmConfig.java代碼如下:定義FTP伺服器參數,包括登錄的用戶名密碼之類的。

package ftpDemo;

public class KmConfig {

//主機ip

private String FtpHost = "";

//埠號

private int FtpPort;

//ftp用戶名

private String FtpUser = "";

//ftp密碼

private String FtpPassword = "";

//ftp中的目錄

private String FtpPath = "";

public String getFtpHost() {

return FtpHost;

}

public void setFtpHost(String ftpHost) {

FtpHost = ftpHost;

}

public int getFtpPort() {

return FtpPort;

}

public void setFtpPort(int ftpPort) {

FtpPort = ftpPort;

}

public String getFtpUser() {

return FtpUser;

}

public void setFtpUser(String ftpUser) {

FtpUser = ftpUser;

}

public String getFtpPassword() {

return FtpPassword;

}

public void setFtpPassword(String ftpPassword) {

FtpPassword = ftpPassword;

}

public String getFtpPath() {

return FtpPath;

}

public void setFtpPath(String ftpPath) {

FtpPath = ftpPath;

}

}

(3):下面是測試代碼:

❽ 關於JAVA FTP連接後文件列表中的中文是亂碼

需要設置文件傳輸的格式,有2中格式 1:asicc 。2:binary格式 也就是二進制格式,並且ftpClient提供了相應的方法,asicc(),barry(),你要在連接ftp的時候加上此方法,ftpClient.binary();

❾ 請問有java上傳文件到ftp伺服器的demo嗎,感激不盡

/**
* 依賴commons-net-3.4.jar, commons-io-2.4.jar
*/
public class FtpUtils {
/**
* 上傳
* @param host FTP地址
* @param port 埠ftp默認22,sftp默認23
* @param user ftp用戶名
* @param pwd ftp密碼
* @param destPath FTP文件保存路徑
* @param fileName ftp保存文件名稱
* @param file 需要上傳的文件
*/
public static void upload(String host, int port,String user, String pwd, String destPath, String fileName, File file){
FTPClient ftp = null;
InputStream fis = null;
try {
//1.建立連接
ftp = new FTPClient();
ftp.connect(host, port);
//2.驗證連接地址
int reply = ftp.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
return;
}
//3.登錄
ftp.login(user, pwd);
//設置上傳路徑、緩存、字元集、文件類型等
ftp.changeWorkingDirectory(destPath);
ftp.setBufferSize(1024);
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//4.上傳
fis = new FileInputStream(file);
ftp.storeFile(fileName, fis);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(fis);
try {
if(ftp.isAvailable()){
ftp.logout();
}
if(ftp.isConnected()){
ftp.disconnect();
}
//刪除上傳臨時文件
if(null != file && file.exists()){
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

❿ 如何用java連接到ftp上

現在已經封裝好了的方法,不需要任何其他知識即可連接的。只需要知道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;

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

熱點內容
對等區域網與客戶機伺服器有什麼不同 發布:2024-05-05 07:51:15 瀏覽:175
win7Linux修復linux 發布:2024-05-05 07:47:17 瀏覽:61
oracle批處理腳本 發布:2024-05-05 07:32:20 瀏覽:393
linuxftp響應慢 發布:2024-05-05 07:23:03 瀏覽:803
sql查詢所有欄位 發布:2024-05-05 07:22:07 瀏覽:672
電腦的存儲符號 發布:2024-05-05 07:15:21 瀏覽:132
sql轉換成數據類型int時失敗 發布:2024-05-05 06:29:21 瀏覽:827
蘋果手機視頻怎麼加密 發布:2024-05-05 06:22:08 瀏覽:919
java反編譯工具使用方法 發布:2024-05-05 06:00:38 瀏覽:218
戀人源碼 發布:2024-05-05 05:53:33 瀏覽:167