1
나는 스윙 FTP 클라이언트를 구축 중입니다.
다음은 JFrame의 내 코드입니다 : -
ftp 서버에서 하위 디렉토리를 찾는 방법
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();
}
}
}
}
그리고이는
처럼 내 출력은 내 ftp 서버의 디렉토리는 이제 서브 디렉토리를 탐색하려고 할 때 부모 디렉토리를 클릭하고, 파일 다운로드를위한 진행률 막대를 추가하고 싶습니다.