gpt4 book ai didi

java - 如何浏览 ftp 服务器上的子目录

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:11 25 4
gpt4 key购买 nike

我正在构建一个 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.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;

}
}

}



这是我的 ftp 类代码

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();
}
}


}


}



我的输出就像 enter image description here

这些是我的 ftp 服务器的目录,现在我想在单击父目录时浏览子目录,我还想添加文件下载进度条有人可以帮忙吗?

最佳答案

我已经通过构造函数链接解决了我的问题。

这是第二个构造函数

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);
}

关于java - 如何浏览 ftp 服务器上的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com