Java 如何在ftp服务器上浏览子目录
我正在构建一个swing FTP客户端。Java 如何在ftp服务器上浏览子目录,java,swing,ftp,jtable,jprogressbar,Java,Swing,Ftp,Jtable,Jprogressbar,我正在构建一个swing FTP客户端。以下是我的jframe代码:- package jframe; import jframe.swing.download.*; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import test.FtpClient; import javax.swing.*; import javax.swing.table.TableMo
以下是我的jframe代码:-
package jframe;
import jframe.swing.download.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import test.FtpClient;
import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.tree.DefaultMutableTreeNode;
public class UndecoratedFrameDemo {
private static Point point = new Point();
ArrayList arrayList;
static String server = "";
static int port = 21;
static String user = "";
static String pass = "";
JPopupMenu popup;
public UndecoratedFrameDemo()
{
final Ftp_by_apache ftpByApache=new Ftp_by_apache(server,user,pass);
arrayList=ftpByApache.getAllFile("/");
final JFrame frame = new JFrame("FTP Client By MPST");
frame.setUndecorated(false);
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Point p = frame.getLocation();
frame.setLocation(p.x + e.getX() - point.x,
p.y + e.getY() - point.y);
}
});
frame.setSize(700, 500);
frame.setLocation(300, 150);
frame.setLayout(new BorderLayout());
Image icon = new javax.swing.ImageIcon("ftp-big-icon.jpg").getImage();
frame.setIconImage(icon);
Container pane=frame.getContentPane();
pane.setLayout(new BorderLayout());
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
menuBar.add(file);
JMenuItem New = new JMenuItem("New Server");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for new ftp server*/
}
});
file.add(New);
JMenuItem rename = new JMenuItem("Rename");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for rename*/
}
});
file.add(rename);
JMenuItem delete = new JMenuItem("Delete");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for delete*/
}
});
file.add(delete);
JMenuItem connect = new JMenuItem("Connect");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for connect to differnt ftp*/
}
});
file.add(connect);
JMenuItem item = new JMenuItem("Exit");
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(item);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenuItem copy = new JMenuItem("Copy");
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
/* code for copy*/
}
});
edit.add(copy);
JMenuItem paste = new JMenuItem("Paste");
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
/* code for Paste*/
}
});
edit.add(paste);
JMenuItem mkdir = new JMenuItem("New Directory");
New.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(mkdir);
popup = new JPopupMenu();
JMenuItem popupcopy= new JMenuItem("Copy");
popup.add(popupcopy );
JMenuItem popuprename= new JMenuItem("Rename");
popup.add( popuprename );
JMenuItem popupdelete= new JMenuItem("Delete");
popup.add( popupdelete );
JMenuItem menuItem = new JMenuItem("Open");
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
Component c = (Component)event.getSource();
JPopupMenu popup = (JPopupMenu)c.getParent();
JTable table = (JTable)popup.getInvoker();
System.out.println(table.getSelectedRow() + " : " + table.getSelectedColumn());
if(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()+1).equals("File Folder"))
{
System.out.println("File Folder Clicked");
SwingUtilities.updateComponentTreeUI(frame);
}
else
{
try {
ftpByApache.download(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString(),"X:/");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
popup.add(menuItem);
FileTableModel fileTableModel =new FileTableModel(arrayList) ;
JTable table = new JTable(fileTableModel)
{
public boolean isCellEditable(int data, int column)
{
return false;
}
};
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("pressed");
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
JTable source = (JTable) e.getSource();
int row = source.rowAtPoint(e.getPoint());
int column = source.columnAtPoint(e.getPoint());
if (!source.isRowSelected(row))
source.changeSelection(row, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
public static void main(String[] args) {
new UndecoratedFrameDemo();
}
public String[] getDir(String dir){ //Gets all of the directories from a given directory and returns them as a String Array
String[] directories;
try{
FTPClient ftpClient = new FTPClient();
FTPFile[] objects = ftpClient.listDirectories(dir);
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
directories = new String[objects.length];
for(int i=0; i<objects.length; i++){
directories[i]=objects[i].getName();
}
return directories;
} catch (IOException ex) {
String[] dir1={};
System.out.println("ERROR");
return dir1;
}
}
}
jframe包;
导入jframe.swing.download.*;
导入org.apache.commons.net.ftp.FTPClient;
导入org.apache.commons.net.ftp.FTPFile;
导入test.ftp客户端;
导入javax.swing.*;
导入javax.swing.table.TableModel;
导入javax.swing.tree.DefaultMutableTreeNode;
导入javax.swing.tree.DefaultTreeModel;
导入java.awt.event.*;
导入java.awt.*;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.Enumeration;
导入javax.swing.tree.DefaultMutableTreeNode;
公共类未修饰的框架演示{
私有静态点=新点();
ArrayList ArrayList;
静态字符串服务器=”;
静态int端口=21;
静态字符串user=“”;
静态字符串传递=”;
jpopmpmenu弹出窗口;
公共未修饰框架演示()
{
最终Ftp_by_apache ftpByApache=新Ftp_by_apache(服务器、用户、通行证);
arrayList=ftpByApache.getAllFile(“/”);
最终JFrame=新JFrame(“MPST的FTP客户端”);
框架。设置未装饰(假);
frame.addMouseListener(新的MouseAdapter(){
公共无效鼠标按下(MouseEvent e){
点x=e.getX();
点y=e.getY();
}
});
frame.addMouseMotionListener(新的MouseMotionAdapter(){
公共无效鼠标标记(鼠标事件e){
p点=frame.getLocation();
frame.setLocation(p.x+e.getX()-point.x,
p、 y+e.getY()-点y);
}
});
框架设置尺寸(700500);
帧设置位置(300150);
frame.setLayout(新的BorderLayout());
Image icon=newjavax.swing.ImageIcon(“ftp big icon.jpg”).getImage();
frame.setIconImage(图标);
容器窗格=frame.getContentPane();
setLayout(新的BorderLayout());
JMenuBar menuBar=新的JMenuBar();
JMenu文件=新JMenu(“文件”);
menuBar.add(文件);
JMenuItem New=新JMenuItem(“新服务器”);
New.addActionListener(New ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
/*新ftp服务器的代码*/
}
});
文件。添加(新);
JMenuItem rename=新的JMenuItem(“重命名”);
New.addActionListener(New ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
/*重命名代码*/
}
});
添加(重命名);
JMenuItem delete=新的JMenuItem(“删除”);
New.addActionListener(New ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
/*删除代码*/
}
});
文件。添加(删除);
JMenuItem connect=新的JMenuItem(“连接”);
New.addActionListener(New ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
/*连接到不同ftp的代码*/
}
});
文件。添加(连接);
JMenuItem=新的JMenuItem(“退出”);
item.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
系统出口(0);
}
});
文件。添加(项目);
JMenu edit=新JMenu(“编辑”);
菜单栏。添加(编辑);
JMenuItem副本=新的JMenuItem(“副本”);
item.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
/*复制代码*/
}
});
编辑。添加(副本);
JMenuItem粘贴=新的JMenuItem(“粘贴”);
item.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
/*粘贴代码*/
}
});
编辑、添加(粘贴);
JMenuItem mkdir=新的JMenuItem(“新目录”);
New.addActionListener(New ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
系统出口(0);
}
});
添加(mkdir);
popup=new JPopupMenu();
JMenuItem popupcopy=新的JMenuItem(“副本”);
popup.add(popupcopy);
JMenuItem popuprename=新的JMenuItem(“重命名”);
popup.add(popuprename);
JMenuItem popupdelete=新的JMenuItem(“删除”);
popup.add(popupdelete);
JMenuItem菜单项=新的JMenuItem(“打开”);
menuItem.addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件){
组件c=(组件)事件.getSource();
JPopupMenu popup=(JPopupMenu)c.getParent();
JTable table=(JTable)popup.getInvoker();
System.out.println(table.getSelectedRow()+“:”+table.getSelectedColumn());
if(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()+1).equals(“文件夹”))
{
System.out.println(“单击文件夹”);
SwingUtilities.updateComponentTreeUI(框架);
}
其他的
{
试一试{
ftpByApache.download(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString(),“X:/”;
}
捕获(例外e)
{
e、 printStackTrace();
}
}
}
});
添加(菜单项);
FileTableModel FileTableModel=新的FileTableModel(arrayList);
JTable table=新的JTable(fileTableModel)
{
公共布尔值可编辑(整型数据,整型列)
{
返回false;
}
};
表.addMouseListener(新的MouseAdapter(){
公共无效鼠标按下(MouseEvent e){
系统输出打印项次(“按下”);
}
公共无效MouseEvent(MouseEvent e){
如果(如isPopupTrigger()){
JTable source=(JTable)e.getSource();
int row=source.rowAtPoint(例如getPoint());
内科鲁
package jframe;
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 java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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();
//
f.enterLocalPassiveMode();
this.get_connection(url, username, password);
}
public String printTime(String time) {
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss");
try {
String timePart = time.split(" ")[1];
Date modificationTime = dateFormat.parse(timePart);
System.out.println("File modification time: " + modificationTime);
return modificationTime.toString();
} catch (ParseException ex) {
ex.printStackTrace();
return "undefined";
}
}
//
public void get_connection(String url, String username, String password) {
try {
f.connect(url);
System.out.println("connect success!");
f.setControlEncoding("GBK");
boolean login = f.login(username, password);
if (login)
System.out.println("logged In");
else
System.out.println("Login Failed!");
} 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("Log out successfull!");
} else {
System.out.println("try again!");
}
if (f.isConnected())
try {
System.out.println("connection is alive!");
f.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
//
public ArrayList getAllFile(String dir) {
f.enterLocalPassiveMode();
/* try {
f.changeWorkingDirectory(dir);
}
catch (Exception e)
{
e.printStackTrace();
}*/
DateFormat dateFormater = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
ArrayList<ArrayList> arrayList= new ArrayList<ArrayList>();
FTPFile[] files = null;
try {
files = f.listFiles();
if(f.isAvailable())
{
System.out.println("connected");
}
System.out.println("length: "+files.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (FTPFile file : files) {
ArrayList arrayList1=new ArrayList();
arrayList1.add(file.getName());
if (file.isDirectory())
{
arrayList1.add("File Folder");
}
else if (file.getName().endsWith(".exe"))
{
arrayList1.add("Application");
}
else if (file.getName().endsWith(".zip"))
{
arrayList1.add("Compressed (Zip Folder)");
}
else if (file.getName().endsWith(".xls")||file.getName().endsWith(".xlsx")||file.getName().endsWith(".doc")||file.getName().endsWith(".docx")||file.getName().endsWith(".rtf"))
{
arrayList1.add("Microsoft Office Document");
}
else if (file.getName().endsWith(".sql"))
{
arrayList1.add("SQL File");
}
else if (file.getName().endsWith(".txt"))
{
arrayList1.add("Text Document");
}
else if (file.getName().endsWith(".pdf"))
{
arrayList1.add("PDF Document");
}
else
{
arrayList1.add("File");
}
arrayList1.add(dateFormater.format(file.getTimestamp().getTime()));
arrayList1.add(file.getSize()+" Kb");
arrayList.add(arrayList1);
if(file.isDirectory())
System.out.println(file.getName()+": Directory");
if(file.isFile())
System.out.println(file.getName()+": File");
}
System.out.println(arrayList);
return arrayList;
}
//
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("file uploaded successfully");
if (input != null)
input.close();
}
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();
}
}
}
}
public UndecoratedFrameDemo(final String childdir,Ftp_by_apache ftpByApache2)
{
final Ftp_by_apache ftpByApache12=ftpByApache2;
arrayList1=ftpByApache12.getSublFile(childdir);
System.out.println("initial directory: " + childdir);
final JFrame frame = new JFrame("FTP Client By MPST");
frame.setUndecorated(false);
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Point p = frame.getLocation();
frame.setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
frame.setSize(700, 500);
frame.setLocation(300, 150);
frame.setLayout(new BorderLayout());
Image icon = new javax.swing.ImageIcon("ftp-big-icon.jpg").getImage();
frame.setIconImage(icon);
Container pane=frame.getContentPane();
pane.setLayout(new BorderLayout());
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
menuBar.add(file);
JMenuItem New = new JMenuItem("New Server");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for new ftp server*/
}
});
file.add(New);
JMenuItem rename = new JMenuItem("Rename");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for rename*/
}
});
file.add(rename);
JMenuItem delete = new JMenuItem("Delete");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for delete*/
}
});
file.add(delete);
JMenuItem connect = new JMenuItem("Connect");
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*code for connect to differnt ftp*/
}
});
file.add(connect);
JMenuItem item = new JMenuItem("Exit");
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(item);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenuItem copy = new JMenuItem("Copy");
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
/* code for copy*/
}
});
edit.add(copy);
JMenuItem paste = new JMenuItem("Paste");
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
/* code for Paste*/
}
});
edit.add(paste);
JMenuItem mkdir = new JMenuItem("New Directory");
New.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(mkdir);
popup = new JPopupMenu();
JMenuItem popupcopy= new JMenuItem("Copy");
popup.add(popupcopy );
JMenuItem popuprename= new JMenuItem("Rename");
popup.add( popuprename );
JMenuItem popupdelete= new JMenuItem("Delete");
popup.add( popupdelete );
JMenuItem menuItem = new JMenuItem("Open");
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
Component c = (Component)event.getSource();
JPopupMenu popup = (JPopupMenu)c.getParent();
JTable table = (JTable)popup.getInvoker();
System.out.println(table.getSelectedRow() + " : " + table.getSelectedColumn());
if(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()+1).equals("File Folder"))
{
System.out.println("File Folder Clicked");
new UndecoratedFrameDemo(childdir+"/"+table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString(),ftpByApache12);
// frame.add(table1);
frame.hide();
}
else
{
try {
ftpByApache12.download(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString(),"X:/");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
popup.add(menuItem);
FileTableModel1 fileTableModel1 =new FileTableModel1(arrayList1) ;
JTable table = new JTable(fileTableModel1)
{
public boolean isCellEditable(int data, int column)
{
return false;
}
};
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("pressed");
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
JTable source = (JTable) e.getSource();
int row = source.rowAtPoint(e.getPoint());
int column = source.columnAtPoint(e.getPoint());
if (!source.isRowSelected(row))
source.changeSelection(row, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
// JFilePicker filePicker = new JFilePicker("Save file to: ","Browse...");
// frame.getContentPane().add(filePicker);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}