首页 > 代码库 > 简单的FTP上传下载(java实现)

简单的FTP上传下载(java实现)

/**
*阅读前请自己在win7上建立FTP主机
*具体步骤如:http://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html
* 然后将以下FTP,username,password分别改成你的FTP ip地址 用户名 密码即可
* 本例子用了apche的commons-net-3.3.jar以方便FTP的访问 请手动buid -path
* 待完成版 刷新按钮 登录 都还没有做 而且上传 下载 完成后都需要重新运行
* 2014-05-07 
* **/

 

一共3个类

 

  1 import java.awt.EventQueue;
  2 
  3 import javax.swing.JFrame;
  4 import java.awt.BorderLayout;
  5 import javax.swing.JTable;
  6 import javax.swing.border.BevelBorder;
  7 import javax.swing.JFileChooser;
  8 import javax.swing.JScrollPane;
  9 import javax.swing.JTextField;
 10 import javax.swing.JButton;
 11 import javax.swing.JRadioButton;
 12 import javax.swing.JTextArea;
 13 import javax.swing.JLabel;
 14 import java.awt.event.ActionListener;
 15 import java.awt.event.ActionEvent;
 16 import java.awt.Color;
 17 import java.awt.Font;
 18 import javax.swing.SwingConstants;
 19 import javax.swing.UIManager;
 20 import java.awt.Toolkit;
 21 import javax.swing.table.DefaultTableModel;
 22 import javax.swing.border.CompoundBorder;
 23 import javax.swing.border.LineBorder;
 24 import javax.swing.filechooser.FileSystemView;
 25 import javax.swing.JScrollBar;
 26 
 27 import org.apache.commons.net.ftp.FTPFile;
 28 
 29 import java.awt.ScrollPane;
 30 import java.awt.Label;
 31 import java.io.File;
 32 import java.io.IOException;
 33 import java.util.ArrayList;
 34 import java.util.Date;
 35 import java.util.Vector;
 36 import java.awt.Scrollbar;
 37 
 38 public class Frame_Main implements ActionListener{
 39 
 40     
 41     //初始化参数--------------------------------
 42         static FTPFile[] file;
 43         static String FTP="192.168.1.86";
 44         static String username="huanglizhe";
 45         static String password="78883579";
 46     //初始化参数--------------------------------
 47     
 48     
 49     private JFrame frame;
 50     private JTable table;
 51     static Ftp_by_apache ftp;
 52     public static Ftp_by_apache getFtp() {
 53         return ftp;
 54     }
 55     
 56     /**
 57      * Launch the application.
 58      */
 59     public static void main(String[] args) {
 60         
 61          ftp=new Ftp_by_apache(FTP,username,password);
 62          file=ftp.getAllFile();
 63         
 64         
 65         
 66         EventQueue.invokeLater(new Runnable() {
 67             public void run() {
 68                 try {
 69                     Frame_Main window = new Frame_Main();
 70                     window.frame.setVisible(true);
 71                 } catch (Exception e) {
 72                     e.printStackTrace();
 73                 }
 74             }
 75         });
 76         
 77     }
 78 
 79     /**
 80      * Create the application.
 81      */
 82     public Frame_Main() {
 83         initialize();
 84     }
 85 
 86     /**
 87      * Initialize the contents of the frame.
 88      */
 89     private void initialize() {
 90         frame = new JFrame();
 91         frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Frame_Main.class.getResource("/com/sun/java/swing/plaf/windows/icons/UpFolder.gif")));
 92         frame.setTitle("FTP");
 93         frame.setBounds(100, 100, 470, 534);
 94         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 95         frame.getContentPane().setLayout(null);
 96         
 97         //上传按钮--------------------------------------------------
 98         JButton upload = new JButton("\u4E0A\u4F20");
 99         upload.setFont(new Font("宋体", Font.PLAIN, 12));
100         upload.setBackground(UIManager.getColor("Button.highlight"));
101         upload.addActionListener(new ActionListener() {
102             public void actionPerformed(ActionEvent arg0) {
103                 //上传点击按钮触发------------------------------------
104                 System.out.println("上传!!!!!");
105                 int result = 0;  
106                 File file = null;  
107                 String path = null;  
108                 JFileChooser fileChooser = new JFileChooser();  
109                 FileSystemView fsv = FileSystemView.getFileSystemView(); 
110                 System.out.println(fsv.getHomeDirectory());                //得到桌面路径  
111                 fileChooser.setCurrentDirectory(fsv.getHomeDirectory());  
112                 fileChooser.setDialogTitle("请选择要上传的文件...");  
113                 fileChooser.setApproveButtonText("确定");  
114                 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
115                 result = fileChooser.showOpenDialog(null);  
116                 if (JFileChooser.APPROVE_OPTION == result) {  
117                     path=fileChooser.getSelectedFile().getPath();  
118                     System.out.println("path: "+path);
119                     try {
120                         //下载
121                         ftp.upload(path);
122                     } catch (IOException e1) {
123                         // TODO Auto-generated catch block
124                         e1.printStackTrace();
125                     }
126                     finally{
127                         
128                         ftp.close_connection();
129                     }
130                     } 
131                 //上传点击按钮触发------------------------------------
132             }
133         });
134         upload.setBounds(195, 15, 82, 23);
135         frame.getContentPane().add(upload);
136         //上传按钮--------------------------------------------------
137         
138         
139         
140         //刷新按钮--------------------------------------------------
141         JButton refresh = new JButton("\u5237\u65B0");
142         refresh.addActionListener(new ActionListener() {
143             public void actionPerformed(ActionEvent arg0) {
144             }
145         });
146         refresh.setFont(new Font("宋体", Font.PLAIN, 12));
147         refresh.setBackground(UIManager.getColor("Button.highlight"));
148         refresh.setBounds(312, 15, 82, 23);
149         frame.getContentPane().add(refresh);
150         //刷新按钮--------------------------------------------------
151         
152         
153         
154         //显示基本信息(FTP username)-----------------------------------------------
155         JLabel lblNewLabel = new JLabel("FTP\u5730\u5740");
156         lblNewLabel.setBounds(32, 10, 54, 15);
157         frame.getContentPane().add(lblNewLabel);
158         
159         JLabel lblNewLabel_1 = new JLabel("\u7528\u6237\u540D");
160         lblNewLabel_1.setBounds(32, 35, 54, 15);
161         frame.getContentPane().add(lblNewLabel_1);
162         
163         JLabel address = new JLabel(FTP);
164         address.setBounds(110, 10, 75, 15);
165         frame.getContentPane().add(address);
166         
167         JLabel name = new JLabel(username);
168         name.setBounds(110, 35, 82, 15);
169         frame.getContentPane().add(name);
170         //显示基本信息-----------------------------------------------
171         
172         
173         //table数据初始化  从FTP读取所有文件
174         String[][] data1=new String[file.length][4];
175          for(int row=0;row<file.length;row++)
176          {
177              
178                  data1[row][0]=file[row].getName();
179                  if(file[row].isDirectory())
180                     {
181                      data1[row][1]="文件夹";
182                     }
183                     else if(file[row].isFile()){
184                         String[] geshi=file[row].getName().split("\\.");
185                         data1[row][1]=geshi[1];    
186                     }
187                  data1[row][2]=file[row].getSize()+"";
188                  data1[row][3]="下载";
189          } 
190          
191         
192         
193         //table列名-----------------------------------------------------
194         String[] columnNames = {"文件", "文件类型", "文件大小(字节)", ""  };  
195         DefaultTableModel model = new DefaultTableModel();
196         model.setDataVector(data1, columnNames);
197         
198         //加滚动条--------------------------------------------------------
199         JScrollPane scrollPane = new JScrollPane();
200         scrollPane.setBounds(32, 73, 362, 384);
201         frame.getContentPane().add(scrollPane);
202           //加滚动条-----------------------------------------------------
203           
204         //table功能------------------------------------------------------
205         table = new JTable(model);
206         scrollPane.setViewportView(table);
207         table.setColumnSelectionAllowed(true);
208         table.setCellSelectionEnabled(true);
209         table.setFont(new Font("微软雅黑", Font.PLAIN, 12));
210         table.setBorder(new LineBorder(new Color(0, 0, 0)));
211         table.setToolTipText("\u53EF\u4EE5\u70B9\u51FB\u4E0B\u8F7D");
212         
213          //table button初始化(最后一列的按键)--------------------    
214         ButtonColumn buttonsColumn = new ButtonColumn(table, 3);
215       
216     }
217 
218     @Override
219     public void actionPerformed(ActionEvent arg0) {
220         // TODO Auto-generated method stub
221         
222     }
223 }

 

ButtonColumn类 主要实现下载按钮

  1   
  2 import java.awt.Component;  
  3 import java.awt.event.ActionEvent;  
  4 import java.awt.event.ActionListener;  
  5 import java.io.File;
  6 import java.io.IOException;
  7   
  8 import javax.swing.AbstractCellEditor;  
  9 import javax.swing.JButton;  
 10 import javax.swing.JFileChooser;
 11 import javax.swing.JTable;  
 12 import javax.swing.UIManager;  
 13 import javax.swing.filechooser.FileSystemView;
 14 import javax.swing.table.TableCellEditor;  
 15 import javax.swing.table.TableCellRenderer;  
 16 import javax.swing.table.TableColumnModel;  
 17 
 18 import org.apache.commons.net.ftp.FTPFile;
 19   
 20 public class ButtonColumn extends AbstractCellEditor implements  
 21         TableCellRenderer, TableCellEditor, ActionListener {  
 22     JTable table;  
 23     JButton renderButton;  
 24     JButton editButton;  
 25     String text;  
 26   
 27     public ButtonColumn(JTable table, int column) {  
 28         super();  
 29         this.table = table;  
 30         renderButton = new JButton();  
 31         editButton = new JButton();  
 32         editButton.setFocusPainted(false);  
 33         editButton.addActionListener(this);  
 34   
 35         TableColumnModel columnModel = table.getColumnModel();  
 36         columnModel.getColumn(column).setCellRenderer(this);  
 37         columnModel.getColumn(column).setCellEditor(this);  
 38     }  
 39   
 40     public Component getTableCellRendererComponent(JTable table, Object value,  
 41             boolean isSelected, boolean hasFocus, int row, int column) {  
 42         if (hasFocus) {  
 43             renderButton.setForeground(table.getForeground());  
 44             renderButton.setBackground(UIManager.getColor("Button.background"));  
 45         } else if (isSelected) {  
 46             renderButton.setForeground(table.getSelectionForeground());  
 47             renderButton.setBackground(table.getSelectionBackground());  
 48         } else {  
 49             renderButton.setForeground(table.getForeground());  
 50             renderButton.setBackground(UIManager.getColor("Button.background"));  
 51         }  
 52   
 53         renderButton.setText((value =http://www.mamicode.com/= null) ? " " : value.toString());  
 54         return renderButton;  
 55     }  
 56   
 57     public Component getTableCellEditorComponent(JTable table, Object value,  
 58             boolean isSelected, int row, int column) {  
 59         text = (value =http://www.mamicode.com/= null) ? " " : value.toString();  
 60         editButton.setText(text);  
 61         return editButton;  
 62     }  
 63   
 64     public Object getCellEditorValue() {  
 65         return text;  
 66     }  
 67   
 68     public void actionPerformed(ActionEvent e) {  
 69         fireEditingStopped();  
 70 //        System.out.println(e.getActionCommand() + "   :    "  
 71 //                + table.getSelectedRow()); 
 72         FTPFile[]  file1=Frame_Main.getFtp().getAllFile();
 73         String from_file_name=file1[table.getSelectedRow()].getName();
 74         int result = 0;  
 75         File file = null;  
 76         String path = null;  
 77         JFileChooser fileChooser = new JFileChooser();  
 78         FileSystemView fsv = FileSystemView.getFileSystemView();
 79         fsv.createFileObject(from_file_name);
 80         //System.out.println(fsv.getHomeDirectory());  
 81         fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
 82         //fileChooser.setCurrentDirectory(new File(from_file_name));  
 83         fileChooser.setDialogTitle("另存为:");  
 84         //fileChooser.setApproveButtonText("保存");   
 85         result = fileChooser.showSaveDialog(null);
 86         if (JFileChooser.APPROVE_OPTION == result) {  
 87             path=fileChooser.getSelectedFile().getPath()+"\\"; //加"\\"是为了防止在桌面的时候C:destop最后没有\ 
 88             System.out.println("path: "+path);
 89             System.out.println("from_file_name:"+from_file_name);
 90             try {
 91                 Frame_Main.getFtp().download(from_file_name, path);
 92                 System.out.println("下载成功! ");
 93 
 94             } catch (IOException e1) {
 95                 // TODO Auto-generated catch block
 96                 e1.printStackTrace();
 97             }
 98             finally{
 99                 
100                 Frame_Main.getFtp().close_connection();
101             }
102             } 
103              
104     }  
105  
106     }

 

Ftp_by_apache服务类 主要实现连接 上传 下载 注销功能

  1 package com.huang.ftp;
  2 import java.io.FileInputStream;
  3 import java.io.FileNotFoundException;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.io.OutputStream;
  8 
  9 import javax.imageio.stream.FileImageInputStream;
 10 
 11 import org.apache.commons.net.*; 
 12 import org.apache.commons.net.ftp.FTPClient;
 13 import org.apache.commons.net.ftp.FTPFile;
 14 
 15 
 16 public class Ftp_by_apache {
 17     
 18     
 19     FTPClient f=null;
 20     //默认构造函数
 21     public Ftp_by_apache(String url,String username,String password)
 22     {
 23         f=new FTPClient();
 24         //得到连接
 25         this.get_connection(url,username,password);
 26         
 27         
 28         
 29         
 30     }
 31     
 32     
 33     //连接服务器方法
 34     public void get_connection(String url,String username,String password){
 35         
 36     
 37         try {
 38             //连接指定服务器,默认端口为21  
 39             f.connect(url);
 40             System.out.println("connect success!");
 41             
 42             //设置链接编码,windows主机UTF-8会乱码,需要使用GBK或gb2312编码  
 43             f.setControlEncoding("GBK");
 44             
 45             //登录
 46             boolean login=f.login(username, password);
 47             if(login)
 48                 System.out.println("登录成功!");
 49             else
 50                 System.out.println("登录失败!");
 51         
 52         }
 53         catch (IOException e) {
 54             
 55             e.printStackTrace();
 56         }
 57         
 58         
 59     }    
 60     
 61     public void close_connection() {
 62         
 63          boolean logout=false;
 64         try {
 65             logout = f.logout();
 66         } catch (IOException e1) {
 67             // TODO Auto-generated catch block
 68             e1.printStackTrace();
 69         }  
 70          if (logout) {  
 71              System.out.println("注销成功!");  
 72          } else {  
 73              System.out.println("注销失败!");  
 74          }  
 75         
 76         if(f.isConnected())
 77             try {
 78                 System.out.println("关闭连接!");
 79                 f.disconnect();
 80             } catch (IOException e) {
 81             
 82                 e.printStackTrace();
 83             }
 84         
 85     }
 86     
 87     
 88     //获取所有文件和文件夹的名字
 89     public FTPFile[] getAllFile(){
 90         
 91         
 92         FTPFile[] files = null;
 93         try {
 94             files = f.listFiles();
 95         } catch (IOException e) {
 96             // TODO Auto-generated catch block
 97             e.printStackTrace();
 98         }
 99         
100         for(FTPFile file:files)
101         {
102             
103 //            if(file.isDirectory())
104 //                System.out.println(file.getName()+"是文件夹");
105 //            if(file.isFile())
106 //                System.out.println(file.getName()+"是文件");
107         }
108         return files;
109         
110     }
111     
112     
113     //生成InputStream用于上传本地文件  
114     public void upload(String File_path) throws IOException{
115         
116         InputStream input=null;
117         String[] File_name = null;
118         try {
119             input = new FileInputStream(File_path);
120             File_name=File_path.split("\\\\");
121             System.out.println(File_name[File_name.length-1]);
122         } catch (FileNotFoundException e) {
123             // TODO Auto-generated catch block
124             e.printStackTrace();
125         }
126         
127          //上传文件  
128         System.out.println(File_name[File_name.length-1]);
129         f.storeFile(File_name[File_name.length-1], input);
130         System.out.println("上传成功!");
131         
132         if(input!=null)
133         input.close();
134         
135         
136         
137     }
138     
139     
140     //下载 from_file_name是下载的文件名,to_path是下载到的路径地址
141     public void download(String from_file_name,String to_path) throws IOException{
142         
143         
144         
145         OutputStream output=null;
146         try {
147             output = new FileOutputStream(to_path+from_file_name);
148         } catch (FileNotFoundException e) {
149             // TODO Auto-generated catch block
150             e.printStackTrace();
151         }
152         f.retrieveFile(from_file_name, output);
153         if(output!=null)
154         {
155             try {
156                 if(output!=null)
157                 output.close();
158             } catch (IOException e) {
159                 // TODO Auto-generated catch block
160                 e.printStackTrace();
161             }
162         }
163         
164         
165     }
166             
167     
168         
169 
170     
171     
172     
173 }