某些数据交换,我们需要通过ftp来完成。有关FTP客户端,Java为我们提供了强大的类库,常见的有 sun.net.ftp.FtpClient和org.apache.commons.net.ftp.FTPClient(apach提供的)。两者都挺好用的,相比而言后者功能更完善一些。sun.net.ftp.FtpClient 可以帮助我们进行一些简单的ftp客户端功能:下载、上传文件。但如遇到创建目录之类的就无能为力了,我们只好利用第三方源码,比com.enterprisedt.net.ftp.FTPClient。但是apach提供的org.apache.commons.net.ftp.FTPClient这些功能做的很全面。
下面我简单介绍下两者的使用方法:
一、sun.net.ftp.FtpClient 的使用示例:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.DefaultListModel;
import javax.swing.JTree;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpLoginException;
public class Ttt extends JFrame implements ActionListener {
FtpClient ftp = null;
private List ftpList = new List();
private List nativeList = new List();
private JPanel FtpClientFrame = new JPanel(new BorderLayout());
private JPanel FtpClientFrameOne = new JPanel(new FlowLayout(
FlowLayout.LEFT));
private JPanel FtpClientFrameTwo = new JPanel(new GridLayout(1, 8));
private JPanel FtpClientFrameThree = new JPanel(new GridLayout(2, 1));
private JPanel FtpClientFrameFour = new JPanel(new GridLayout(1, 2));
// 连接、断开按钮
private JButton linkButton = new JButton("Link");
private JButton breakButton = new JButton("Break");
private JButton uploadButton = new JButton("Upload");
private JButton downloadButton = new JButton("Download");
// 连接状态
private JLabel statusLabel = new JLabel();
// 用户登录
private JLabel urlLabel = new JLabel("Ftp URL:");
private JLabel usernameLabel = new JLabel("username:");
private JLabel passwordLabel = new JLabel("password:");
private JLabel portLabel = new JLabel("port:");
private JTextField urlTextField = new JTextField("10.10.103.21", 10);
private JTextField usernameTextField = new JTextField("gridmiddleware", 10);
private JTextField passwordTextField = new JTextField("three@project", 10);
private JTextField portTextField = new JTextField("6000", 10);
// 本地、远程窗口
DefaultListModel modelList = new DefaultListModel();
public Ttt() {
FtpClientFrameOne.add(linkButton);
FtpClientFrameOne.add(breakButton);
FtpClientFrameOne.add(uploadButton);
FtpClientFrameOne.add(downloadButton);
FtpClientFrameOne.add(statusLabel);
FtpClientFrameTwo.add(urlLabel);
FtpClientFrameTwo.add(urlTextField);
FtpClientFrameTwo.add(usernameLabel);
FtpClientFrameTwo.add(usernameTextField);
FtpClientFrameTwo.add(passwordLabel);
FtpClientFrameTwo.add(passwordTextField);
FtpClientFrameTwo.add(portLabel);
FtpClientFrameTwo.add(portTextField);
FtpClientFrameThree.add(FtpClientFrameOne);
FtpClientFrameThree.add(FtpClientFrameTwo);
FtpClientFrameFour.add(nativeList);
FtpClientFrameFour.add(ftpList);
FtpClientFrame.add(FtpClientFrameThree, "North");
FtpClientFrame.add(FtpClientFrameFour, "Center");
setContentPane(FtpClientFrame);
setTitle("Ftp客户端");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
linkButton.addActionListener(this);
breakButton.addActionListener(this);
uploadButton.addActionListener(this);
downloadButton.addActionListener(this);
}
public String getDir(String path) {
String dirName;
// int ch;
int begin = 55;
dirName = path.substring(begin).trim();
return dirName;
}
public void loadFtpList() {
StringBuffer buf = new StringBuffer();
int ch;
ftpList.removeAll();
try {
TelnetInputStream t = ftp.list();
t.setStickyCRLF(true);
while ((ch = t.read()) >= 0) {
if (ch == '/n') {
ftpList.add(getDir(buf.toString()));
buf.setLength(0);
} else {
buf.append((char) ch);
}
}
} catch (IOException e) {
e.printStackTrace();
}
ftpList.validate();
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == linkButton) {
// 连接Ftp服务器
try {
if (ftp != null)
ftp.closeServer();
statusLabel.setText("连接中,请等待.....");
ftp = new FtpClient(urlTextField.getText(), Integer
.parseInt(portTextField.getText()));
ftp.login(usernameTextField.getText(), passwordTextField
.getText());
ftp.binary();
} catch (FtpLoginException e) {
JOptionPane.showMessageDialog(null, "Login Failure!!!");
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, urlTextField.getText()
+ "Connection Failure!!!");
e.printStackTrace();
} catch (SecurityException e) {
JOptionPane.showMessageDialog(null, "No Purview!!!");
e.printStackTrace();
}
if (urlTextField.getText().equals(""))
JOptionPane.showMessageDialog(null, "Ftp服务器地址不能空!!!");
else if (usernameTextField.getText().equals(""))
JOptionPane.showMessageDialog(null, "用户名不能为空!!!");
else if (passwordTextField.getText().equals(""))
JOptionPane.showMessageDialog(null, "密码不能为空!!!");
else
statusLabel.setText("已连接到Ftp:" + urlTextField.getText());
loadFtpList();
}
if (source == uploadButton) {
//String RWFileDir = "F://gridmiddleware";
TelnetOutputStream outs;
String message = "";
String filepathname = "E://1234.txt";
if (ftp != null) {
statusLabel.setText("正在上传文件");
try {
ftp.cd(ftp.pwd()+"//src");
String fg =new String("E://");
int index = filepathname.lastIndexOf(fg);
String filename = filepathname.substring(index+1);
RandomAccessFile sendFile = new RandomAccessFile(
filepathname, "r");
sendFile.seek(0);
outs = ftp.put(filename);
DataOutputStream outputs = new DataOutputStream(outs);
int ch;
while (sendFile.getFilePointer() < sendFile.length()) {
ch = sendFile.read();
outputs.write(ch);
}
outs.close();
sendFile.close();
message = "上传" + filepathname + "文件成功!";
System.out.println(message);
} catch (IOException e) {
message = "上传失败";
//System.out.println("上传" + filepathname + "文件到" + RWFileDir
//+ "目录失败!"+e);
System.out.println(message);
}
statusLabel.setText(message);
}
}
//下载代码
if (source == downloadButton) {
String filepathname = ftpList.getSelectedItem();
if(filepathname==null)
JOptionPane.showMessageDialog(null, "请选择要下载的文件!!!");
String baddir = "E://download_test//";
String message = "";
if (ftp != null) {
statusLabel.setText("正在下载...");
try {
int ch;
File fi = new File(baddir + filepathname);
RandomAccessFile getFile = new RandomAccessFile(fi, "rw");
getFile.seek(0);
TelnetInputStream fget = ftp.get(filepathname);
DataInputStream puts = new DataInputStream(fget);
while ((ch = puts.read()) >= 0) {
getFile.write(ch);
}
fget.close();
getFile.close();
message = "下载成功!";
System.out.println("下载" + filepathname + "文件到" + baddir
+ "目录成功!");
} catch (IOException e) {
message = "下载失败!";
System.out.println("下载" + filepathname + "文件到" + baddir
+ "目录失败!" + e);
}
}
statusLabel.setText(message);
}
// TODO:以上是我加的代码
if (source == breakButton) {
System.exit(0);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Ttt ftpClientFrame = new Ttt();
}
}
二、org.apache.commons.net.ftp.FTPClient的使用示例:
package org.gridsphere.G2RPbrt.portlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpUtil {
FTPClient ftpClient;
//连接Ftp服务器
public void connectServer(String server, int port, String user,
String password, String path) throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.connect(server, port);
System.out.println("Connected to " + server + ".");
System.out.println(ftpClient.getReplyCode());
ftpClient.login(user, password);
// Path is the sub-path of the FTP path
if (path.length() != 0) {
ftpClient.changeWorkingDirectory(path);
}
}
/**
* 关闭连接
* */
public boolean closeConnect() {
boolean flag = false;
try {
ftpClient.disconnect();
System.out.println(" disconnect success !!! ");
} catch (IOException e) {
System.out.println(" not disconnect !!! ");
System.out.println(e.getMessage());
flag = false;
return flag;
}
return flag;
}
//FTP上传
public boolean uploadFile(String fileName)
throws IOException {
boolean flag = false;
String remoteName;
ftpClient.makeDirectory("pbrt");
ftpClient.changeWorkingDirectory("pbrt");
InputStream iStream = null;
try {
iStream = new FileInputStream(fileName);
remoteName=fileName.substring((fileName.lastIndexOf("//"))+1);
flag = ftpClient.storeFile(remoteName, iStream);
} catch (IOException e) {
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
// 对中文目录名的转化
public static String encode(String str){
try{
String encodeStr=new String(str.getBytes("gb2312"),"iso-8859-1");
return encodeStr;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
//FTP下载,该下载实现了下载一个文件夹的所有文件
public boolean download(String localPath)throws IOException{
boolean flag=false;
ftpClient.changeWorkingDirectory("tif");
String dfn="";
OutputStream oStream = null;
String[] lfn=ftpClient.listNames();
try{
for(int i=0;i<lfn.length;i++){
dfn=localPath+lfn[i];
File outfile = new File(dfn);
oStream = new FileOutputStream(outfile);
flag = ftpClient.retrieveFile(lfn[i], oStream);
}
for(int j=0;j<lfn.length;j++){
ftpClient.deleteFile(lfn[j]);
}
ftpClient.changeWorkingDirectory("//");
ftpClient.removeDirectory("tif");
ftpClient.changeWorkingDirectory("pbrt");
String[] pfn=ftpClient.listNames();
for(int k=0;k<pfn.length;k++){
ftpClient.deleteFile(pfn[k]);
}
ftpClient.changeWorkingDirectory("//");
ftpClient.removeDirectory("pbrt");
}
catch(Exception e){
flag = false;
return flag;
}finally {
oStream.close();
}
return flag;
}
public static void main(String args[]) throws SocketException, IOException {
FtpUtil ffc = new FtpUtil();
ffc.connectServer("10.10.103.21", 6000, "grid",
"grid903", "e://film");
// ffc.uploadFile("D://temp//CGSP-VEGA.exe");
if(ffc.download("D://tif//")){
System.out.println("download success");
};
// System.out.println(ffc.removeDirectory("001"));
ffc.closeConnect();
}
}