大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > Java技巧 > 简单的FTP上传下载(java实现)

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

关键词:上传下载FTPjava  阅读(1826) 赞(15)

[摘要]本文是对简单的FTP上传下载(java实现)的讲解,对学习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个类

 import java.awt.EventQueue;
 import javax.swing.JFrame;
 import java.awt.BorderLayout;
 import javax.swing.JTable;
 import javax.swing.border.BevelBorder;
 import javax.swing.JFileChooser;
 import javax.swing.JScrollPane;
 import javax.swing.JTextField;
 import javax.swing.JButton;
 import javax.swing.JRadioButton;
 import javax.swing.JTextArea;
 import javax.swing.JLabel;
 import java.awt.event.ActionListener;
 import java.awt.event.ActionEvent;
 import java.awt.Color;
 import java.awt.Font;
 import javax.swing.SwingConstants;
 import javax.swing.UIManager;
 import java.awt.Toolkit;
 import javax.swing.table.DefaultTableModel;
 import javax.swing.border.CompoundBorder;
 import javax.swing.border.LineBorder;
 import javax.swing.filechooser.FileSystemView;
 import javax.swing.JScrollBar;
 
 import org.apache.commons.net.ftp.FTPFile;
 
 import java.awt.ScrollPane;
 import java.awt.Label;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.Vector;
 import java.awt.Scrollbar;
 
 public class Frame_Main implements ActionListener{
 
     
     //初始化参数--------------------------------
         static FTPFile[] file;
         static String FTP="192.168.1.86";
         static String username="huanglizhe";
         static String password="78883579";
     //初始化参数--------------------------------
     
     
     private JFrame frame;
     private JTable table;
     static Ftp_by_apache ftp;
     public static Ftp_by_apache getFtp() {
         return ftp;
     }
     
     /**
      * Launch the application.
      */
     public static void main(String[] args) {
         
          ftp=new Ftp_by_apache(FTP,username,password);
          file=ftp.getAllFile();
         
         
         
         EventQueue.invokeLater(new Runnable() {
             public void run() {
                 try {
                     Frame_Main window = new Frame_Main();
                     window.frame.setVisible(true);
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         });
         
     }
 
     /**
      * Create the application.
      */
     public Frame_Main() {
         initialize();
     }
 
     /**
      * Initialize the contents of the frame.
      */
     private void initialize() {
         frame = new JFrame();
         frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Frame_Main.class.getResource("/com/sun/java/swing/plaf/windows/icons/UpFolder.gif")));
         frame.setTitle("FTP");
         frame.setBounds(100, 100, 470, 534);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().setLayout(null);
         
         //上传按钮--------------------------------------------------
         JButton upload = new JButton("\u4E0A\u4F20");
         upload.setFont(new Font("宋体", Font.PLAIN, 12));
         upload.setBackground(UIManager.getColor("Button.highlight"));
         upload.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent arg0) {
                 //上传点击按钮触发------------------------------------
                 System.out.println("上传!!!!!");
                 int result = 0;  
                 File file = null;  
                 String path = null;  
                 JFileChooser fileChooser = new JFileChooser();  
                 FileSystemView fsv = FileSystemView.getFileSystemView(); 
                 System.out.println(fsv.getHomeDirectory());                //得到桌面路径  
                 fileChooser.setCurrentDirectory(fsv.getHomeDirectory());  
                 fileChooser.setDialogTitle("请选择要上传的文件...");  
                 fileChooser.setApproveButtonText("确定");  
                 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
                 result = fileChooser.showOpenDialog(null);  
                 if (JFileChooser.APPROVE_OPTION == result) {  
                     path=fileChooser.getSelectedFile().getPath();  
                     System.out.println("path: "+path);
                     try {
                         //下载
                         ftp.upload(path);
                     } catch (IOException e1) {
                         // TODO Auto-generated catch block
                         e1.printStackTrace();
                     }
                     finally{
                         
                         ftp.close_connection();
                     }
                     } 
                 //上传点击按钮触发------------------------------------
             }
         });
         upload.setBounds(195, 15, 82, 23);
         frame.getContentPane().add(upload);
         //上传按钮--------------------------------------------------
         
         
         
         //刷新按钮--------------------------------------------------
         JButton refresh = new JButton("\u5237\u65B0");
         refresh.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent arg0) {
             }
         });
         refresh.setFont(new Font("宋体", Font.PLAIN, 12));
         refresh.setBackground(UIManager.getColor("Button.highlight"));
         refresh.setBounds(312, 15, 82, 23);
         frame.getContentPane().add(refresh);
         //刷新按钮--------------------------------------------------
         
         
         
         //显示基本信息(FTP username)-----------------------------------------------
         JLabel lblNewLabel = new JLabel("FTP\u5730\u5740");
         lblNewLabel.setBounds(32, 10, 54, 15);
         frame.getContentPane().add(lblNewLabel);
         
         JLabel lblNewLabel_1 = new JLabel("\u7528\u6237\u540D");
         lblNewLabel_1.setBounds(32, 35, 54, 15);
         frame.getContentPane().add(lblNewLabel_1);
         
         JLabel address = new JLabel(FTP);
         address.setBounds(110, 10, 75, 15);
         frame.getContentPane().add(address);
         
         JLabel name = new JLabel(username);
         name.setBounds(110, 35, 82, 15);
         frame.getContentPane().add(name);
         //显示基本信息-----------------------------------------------
         
         
         //table数据初始化  从FTP读取所有文件
         String[][] data1=new String[file.length][4];
          for(int row=0;row<file.length;row++)
          {
              
                  data1[row][0]=file[row].getName();
                  if(file[row].isDirectory())
                     {
                      data1[row][1]="文件夹";
                     }
                     else if(file[row].isFile()){
                         String[] geshi=file[row].getName().split("\\.");
                         data1[row][1]=geshi[1];    
                     }
                  data1[row][2]=file[row].getSize()+"";
                  data1[row][3]="下载";
          } 
          
         
         
         //table列名-----------------------------------------------------
         String[] columnNames = {"文件", "文件类型", "文件大小(字节)", ""  };  
         DefaultTableModel model = new DefaultTableModel();
         model.setDataVector(data1, columnNames);
         
         //加滚动条--------------------------------------------------------
         JScrollPane scrollPane = new JScrollPane();
         scrollPane.setBounds(32, 73, 362, 384);
         frame.getContentPane().add(scrollPane);
           //加滚动条-----------------------------------------------------
           
         //table功能------------------------------------------------------
         table = new JTable(model);
         scrollPane.setViewportView(table);
         table.setColumnSelectionAllowed(true);
         table.setCellSelectionEnabled(true);
         table.setFont(new Font("微软雅黑", Font.PLAIN, 12));
         table.setBorder(new LineBorder(new Color(0, 0, 0)));
         table.setToolTipText("\u53EF\u4EE5\u70B9\u51FB\u4E0B\u8F7D");
         
          //table button初始化(最后一列的按键)--------------------    
         ButtonColumn buttonsColumn = new ButtonColumn(table, 3);
       
     }
 
     @Override
     public void actionPerformed(ActionEvent arg0) {
         // TODO Auto-generated method stub
         
     }
 }

ButtonColumn类 主要实现下载按钮

   
 import java.awt.Component;  
 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import java.io.File;
 import java.io.IOException;
   
 import javax.swing.AbstractCellEditor;  
 import javax.swing.JButton;  
 import javax.swing.JFileChooser;
 import javax.swing.JTable;  
 import javax.swing.UIManager;  
 import javax.swing.filechooser.FileSystemView;
 import javax.swing.table.TableCellEditor;  
 import javax.swing.table.TableCellRenderer;  
 import javax.swing.table.TableColumnModel;  
 
 import org.apache.commons.net.ftp.FTPFile;
   
 public class ButtonColumn extends AbstractCellEditor implements  
         TableCellRenderer, TableCellEditor, ActionListener {  
     JTable table;  
     JButton renderButton;  
     JButton editButton;  
     String text;  
   
     public ButtonColumn(JTable table, int column) {  
         super();  
         this.table = table;  
         renderButton = new JButton();  
         editButton = new JButton();  
         editButton.setFocusPainted(false);  
         editButton.addActionListener(this);  
   
         TableColumnModel columnModel = table.getColumnModel();  
         columnModel.getColumn(column).setCellRenderer(this);  
         columnModel.getColumn(column).setCellEditor(this);  
     }  
   
     public Component getTableCellRendererComponent(JTable table, Object value,  
             boolean isSelected, boolean hasFocus, int row, int column) {  
         if (hasFocus) {  
             renderButton.setForeground(table.getForeground());  
             renderButton.setBackground(UIManager.getColor("Button.background"));  
         } else if (isSelected) {  
             renderButton.setForeground(table.getSelectionForeground());  
             renderButton.setBackground(table.getSelectionBackground());  
         } else {  
             renderButton.setForeground(table.getForeground());  
             renderButton.setBackground(UIManager.getColor("Button.background"));  
         }  
   
         renderButton.setText((value == null) ? " " : value.toString());  
         return renderButton;  
     }  
   
     public Component getTableCellEditorComponent(JTable table, Object value,  
             boolean isSelected, int row, int column) {  
         text = (value == null) ? " " : value.toString();  
         editButton.setText(text);  
         return editButton;  
     }  
   
     public Object getCellEditorValue() {  
         return text;  
     }  
   
     public void actionPerformed(ActionEvent e) {  
         fireEditingStopped();  
 //        System.out.println(e.getActionCommand() + "   :    "  
 //                + table.getSelectedRow()); 
         FTPFile[]  file1=Frame_Main.getFtp().getAllFile();
         String from_file_name=file1[table.getSelectedRow()].getName();
         int result = 0;  
         File file = null;  
         String path = null;  
         JFileChooser fileChooser = new JFileChooser();  
         FileSystemView fsv = FileSystemView.getFileSystemView();
         fsv.createFileObject(from_file_name);
         //System.out.println(fsv.getHomeDirectory());  
         fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
         //fileChooser.setCurrentDirectory(new File(from_file_name));  
         fileChooser.setDialogTitle("另存为:");  
         //fileChooser.setApproveButtonText("保存");   
         result = fileChooser.showSaveDialog(null);
         if (JFileChooser.APPROVE_OPTION == result) {  
             path=fileChooser.getSelectedFile().getPath()+"\\"; //加"\\"是为了防止在桌面的时候C:destop最后没有\ 
             System.out.println("path: "+path);
             System.out.println("from_file_name:"+from_file_name);
             try {
                 Frame_Main.getFtp().download(from_file_name, path);
                 System.out.println("下载成功! ");
 
             } catch (IOException e1) {
                 // TODO Auto-generated catch block
                 e1.printStackTrace();
             }
             finally{
                 
                 Frame_Main.getFtp().close_connection();
             }
             } 
              
     }  
  
     }

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

 package com.huang.ftp;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 
 import javax.imageio.stream.FileImageInputStream;
 
 import org.apache.commons.net.*; 
 import org.apache.commons.net.ftp.FTPClient;
 import org.apache.commons.net.ftp.FTPFile;
 
 
 public class Ftp_by_apache {
     
     
     FTPClient f=null;
     //默认构造函数
     public Ftp_by_apache(String url,String username,String password)
     {
         f=new FTPClient();
         //得到连接
         this.get_connection(url,username,password);
         
         
         
         
     }
     
     
     //连接服务器方法
     public void get_connection(String url,String username,String password){
         
     
         try {
             //连接指定服务器,默认端口为21  
             f.connect(url);
             System.out.println("connect success!");
             
             //设置链接编码,windows主机UTF-8会乱码,需要使用GBK或gb2312编码  
             f.setControlEncoding("GBK");
             
             //登录
             boolean login=f.login(username, password);
             if(login)
                 System.out.println("登录成功!");
             else
                 System.out.println("登录失败!");
         
         }
         catch (IOException e) {
             
             e.printStackTrace();
         }
         
         
     }    
     
     public void close_connection() {
         
          boolean logout=false;
         try {
             logout = f.logout();
         } catch (IOException e1) {
             // TODO Auto-generated catch block
             e1.printStackTrace();
         }  
          if (logout) {  
              System.out.println("注销成功!");  
          } else {  
              System.out.println("注销失败!");  
          }  
         
         if(f.isConnected())
             try {
                 System.out.println("关闭连接!");
                 f.disconnect();
             } catch (IOException e) {
             
                 e.printStackTrace();
             }
         
     }
     
     
     //获取所有文件和文件夹的名字
     public FTPFile[] getAllFile(){
         
         
         FTPFile[] files = null;
         try {
             files = f.listFiles();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         
         for(FTPFile file:files)
         {
             
 //            if(file.isDirectory())
 //                System.out.println(file.getName()+"是文件夹");
 //            if(file.isFile())
 //                System.out.println(file.getName()+"是文件");
         }
         return files;
         
     }
     
     
     //生成InputStream用于上传本地文件  
     public void upload(String File_path) throws IOException{
         
         InputStream input=null;
         String[] File_name = null;
         try {
             input = new FileInputStream(File_path);
             File_name=File_path.split("\\\\");
             System.out.println(File_name[File_name.length-1]);
         } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         
          //上传文件  
         System.out.println(File_name[File_name.length-1]);
         f.storeFile(File_name[File_name.length-1], input);
         System.out.println("上传成功!");
         
         if(input!=null)
         input.close();
         
         
         
     }
     
     
     //下载 from_file_name是下载的文件名,to_path是下载到的路径地址
     public void download(String from_file_name,String to_path) throws IOException{
         
         
         
         OutputStream output=null;
         try {
             output = new FileOutputStream(to_path+from_file_name);
         } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         f.retrieveFile(from_file_name, output);
         if(output!=null)
         {
             try {
                 if(output!=null)
                 output.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
         
         
     }
             
     
         
 
     
     
     
 }


相关评论