简单的FTP上传下载(java实现 swing界面)
/**
*阅读前请自己在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个类 Frame_Main为主函数 图形界面 ButtonColumn是下载键的类 最后一个是FTP服务类
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";
44 static String username="huanglizhe";
45 static String password="123456";
//初始化参数-------------------------------- 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();
}
} } }
运行结果:
1、连接
2、上传
3)下载
简单的FTP上传下载(java实现 swing界面)的更多相关文章
- ftp上传下载 java FTPClient (zhuan)
项目需要,网上搜了搜,很多,但问题也不少,估计转来转去,少了不少东西,而且也情况也不太一样.没办法,只能自己去写一个. 一, 安装sserv-u ftp服务器 版本10.1.0.1 我所设服务器 ...
- JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)
package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...
- Java.ftp上传下载
1:jar的maven的引用: 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- java客户端调用ftp上传下载文件
1:java客户端上传,下载文件. package com.li.utils; import java.io.File; import java.io.FileInputStream; import ...
- 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)
前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...
- ftp上传下载工具类
package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...
- windows系统下ftp上传下载和一些常用命令
先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...
- windows下ftp上传下载和一些常用命令
先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...
- FTP上传下载工具(FlashFXP) v5.5.0 中文版
软件名称: FTP上传下载工具(FlashFXP) 软件语言: 简体中文 授权方式: 免费试用 运行环境: Win 32位/64位 软件大小: 7.4MB 图片预览: 软件简介: FlashFXP 是 ...
随机推荐
- 前端--关于css选择器
css选择器就好像表达式一样,返回一组或者一个html元素,后面的样式声明块应用到返回的元素上.所以可以把css选择器理解为某个或者某一类html元素的抽象的写法. 在讲具体的各种选择器之前要提一下选 ...
- Entity Framework中datetime2 to datetime转换错误
datetime2 to datetime 报错. 因为EF中,DATETIME类型默认是datetime2,数据库默认是datetime. 解决方案: 1.改数据库字段类型为datetime2 2. ...
- PHP学习笔记三十一【const】
<?php //常量都是public类型 // const 常量名=赋值 .变量名不需要加$符号,也不需要要访问修饰符,默认就是public class A{ const TAX_RATE=0. ...
- AsyncTask使用注意事项
AsyncTask是android自带的一个异步处理线程 它带了很多参数 都很方便使用 但是有一些注意事项 1: 官网说明: AsyncTasks should ideally be used for ...
- 1207.1——C语言 函数
函数可以分为无参函数和有参函数. 无参函数的定义 无参函数定义的一般形式如下:返回值类型 函数名(){ 函数体} 说明: 返回值类型可以是C语言中的任意数据类型. 函数名是标识符的一种,命名规 ...
- [原创]Windows下更改特定后缀名以及特定URL前缀的默认打开方式
Windows下,特定后缀名的文件会由特定的应用程序来运行,比如双击readme.txt,通常情况下会由Windows自带的notepad.exe(记事本)打开文件.如果现在安装了记事本以外的其他文本 ...
- mvn多模块开发消除重复依赖造成的打包失败
错误信息: [ERROR] Failed to execute goal on project xiaoyiweifu-core: Could not resolve dependencies for ...
- You and your research
英文版http://www.cs.virginia.edu/~robins/YouAndYourResearch.html 视频版http://www.youtube.com/watch?v=a1zD ...
- display:table-cell的惊天作用,直接惊呆你!
一 display:table-cell介绍 ... 二 用法 (1)高度不固定元素,垂直居中 ... (2)高度不固定列表元素,登高排列 ... (3)宽度不固定元素,平均分配 ...
- js 图片无缝循环
<html> <head> <title>Js图片无缝滚动</title> <style type="text/css"> ...