SWT(JFace) FTP客户端实现_Java编程

Jar包一览:

org.eclipse.jface_3.4.2.M20090107-0800.jar
org.eclipse.swt.win32.win32.x86_3.4.1.v3452b.jar
org.eclipse.core.commands_3.4.0.I20080509-2000.jar
org.eclipse.core.runtime_3.4.0.v20080512.jar
org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
commons-net-ftp-2.0.jar

演示代码如下:

FTPWindow.java

复制代码 代码如下:

package swt_jface.demo13;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ProtocolCommandEvent;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
public class FTPWindow extends ApplicationWindow {

    TableViewer localDirBrowser;
    TableViewer remoteDirBrowser;
    Label labelPathLocal;
    Label labelPathRemote;
    StyledText textLog;
    ConnectionDialog connectionDialog;
    Action actionUpLocalDir;
    Action actionUpRemoteDir;
    Action actionBrowseLocalDir;
    Action actionConnect;
    Action actionDisconnect;
    Action actionDisplayAbout;
    Action actionExit;
    FTPClient ftp;
    ConnectionInfo connectionInfo;
    public FTPWindow(Shell parentShell) {
        super(parentShell);
        createActions();
        addStatusLine();
        //addCoolBar(SWT.FLAT | SWT.RIGHT);
        addToolBar(SWT.FLAT);
        addMenuBar();
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new ProtocolCommandListener() {
            public void protocolCommandSent(ProtocolCommandEvent e) {
                logMessage("> " + e.getCommand(), false);
            }
            public void protocolReplyReceived(ProtocolCommandEvent e) {
                logMessage("< " + e.getMessage(), false);
            }
        });
    }
    private void createActions() {
        actionUpLocalDir = new Action() {
            public void run() {
                if (localDirBrowser.getInput() == null)
                    return;
                File dir = ((File) localDirBrowser.getInput()).getParentFile();
                if (dir != null) {
                    localDirBrowser.setInput(dir);
                    labelPathLocal.setText("Path: " + dir);
                }
            }
        };
        actionUpLocalDir.setText("Up");
        actionUpLocalDir.setToolTipText("Up one level - local dir");
        actionUpLocalDir.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/up.gif"));
        actionBrowseLocalDir = new Action() {
            public void run() {
                DirectoryDialog dialog = new DirectoryDialog(getShell());
                String path = dialog.open();
                if (path == null)
                    return;
                File file = new File(path);
                localDirBrowser.setInput(file);
                labelPathLocal.setText("Path: " + file);
            }
        };
        actionBrowseLocalDir.setText("Browse...");
        actionBrowseLocalDir.setToolTipText("Browse local directory");
        actionBrowseLocalDir.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/browse.gif"));
        actionConnect = new Action() {
            public void run() {
                if (connectionDialog == null)
                    connectionDialog = new ConnectionDialog(FTPWindow.this);
                if (connectionDialog.open() == Dialog.OK) {
                    connectionInfo = connectionDialog.getConnectionInfo();
                    if (connectionInfo == null) {
                        logError("Failed to get connection information.");
                    } else {
                        logMessage("Connecting to " + connectionInfo.host, true);
                        try {
                            ftp.connect(
                                connectionInfo.host,
                                connectionInfo.port);
                            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
                                throw new RuntimeException("FTP server refused connection.");
                            logMessage("Connected to " + connectionInfo.host, true);
                        } catch (Exception e) {
                            logError(e.toString());
                            return;
                        }
                        try {
                            if (ftp
                                .login(
                                    connectionInfo.username,
                                    connectionInfo.password)) {
                                logMessage("Logged in as user: "+ connectionInfo.username, true);
                            }
                            labelPathRemote.setText("Path: " + ftp.printWorkingDirectory());
                            // Lists files.
                            FTPFile[] files = ftp.listFiles();
                            remoteDirBrowser.setInput(files);
                        } catch (IOException e1) {
                            logError(e1.getMessage());
                            try {
                                ftp.disconnect();
                            } catch (IOException e2) {
                                //
                            }
                        }
                    }
                }
            }
        };
        actionConnect.setText("Connect");
        actionConnect.setToolTipText("Connect to remote host");
        actionConnect.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/connect.gif"));
        actionDisconnect = new Action() {
            public void run() {
                try {
                    ftp.logout();
                    ftp.disconnect();
                }catch(Exception e) {
                    logError(e.toString());
                }
            }
        };
        actionDisconnect.setText("Disconnect");
        actionDisconnect.setToolTipText("Disconnect from remote host");
        actionDisconnect.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/stop.gif"));
        actionUpRemoteDir = new Action() {
            public void run() {
                try {
                    if (ftp.changeToParentDirectory()) {
                        labelPathRemote.setText("Path: " + ftp.printWorkingDirectory());
                        FTPFile[] files = ftp.listFiles();
                        remoteDirBrowser.setInput(files);
                    }
                } catch (Exception e) {
                    logError(e.toString());
                }
            }
        };
        actionUpRemoteDir.setText("Up");
        actionUpRemoteDir.setToolTipText("Up one level - remote dir");
        actionUpRemoteDir.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/up.gif"));

        actionDisplayAbout = new Action() {
            public void run() {
                MessageDialog.openInformation(getShell(), "About", "FTP Client v1.0\nAll right reserved by Jack Li Guojie.");
            }
        };
        actionDisplayAbout.setText("About");
        actionDisplayAbout.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/about.gif"));

        actionExit = new Action() {
            public void run() {
                if(! MessageDialog.openConfirm(getShell(), "Confirm", "Are you sure you want to exit?"))
                    return;
                try {
                    ftp.disconnect();
                }catch(Exception e) {
                }
                close();
            }
        };
        actionExit.setText("Exit");
        actionExit.setImageDescriptor(ImageDescriptor.createFromFile(null, "C:/icons/ftp/close.gif"));

    }
    private void dragNDropSupport() {
        int operations = DND.DROP_COPY | DND.DROP_MOVE;
        final DragSource dragSource = new DragSource(remoteDirBrowser.getControl(), operations);
        Transfer[] formats = new Transfer[] { TextTransfer.getInstance()};
        dragSource.setTransfer(formats);
        dragSource.addDragListener(new DragSourceListener() {
            public void dragStart(DragSourceEvent event) {
                System.out.println("DND starts");
                IStructuredSelection selection = (IStructuredSelection) remoteDirBrowser.getSelection();
                FTPFile file = (FTPFile) selection.getFirstElement();
                if (file == null || file.isDirectory()) {
                    event.doit = false;
                }
            }
            public void dragSetData(DragSourceEvent event) {

                if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
                    IStructuredSelection selection = (IStructuredSelection) remoteDirBrowser.getSelection();
                    FTPFile file = (FTPFile) selection.getFirstElement();
                    if (file == null || file.isDirectory()) {
                        event.doit = false;
                    } else {
                        event.data = file.getName();
                    }
                }
            }
            public void dragFinished(DragSourceEvent event) {
            }
        });
        remoteDirBrowser
            .getControl()
            .addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
                dragSource.dispose();
            }
        });
        final DropTarget dropTarget = new DropTarget(localDirBrowser.getControl(), operations);
        dropTarget.setTransfer(formats);
        dropTarget.addDropListener(new DropTargetListener() {
            public void dragEnter(DropTargetEvent event) {
            }
            public void dragLeave(DropTargetEvent event) {
            }
            public void dragOperationChanged(DropTargetEvent event) {
            }
            public void dragOver(DropTargetEvent event) {
            }
            public void drop(DropTargetEvent event) {
                if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
                    String text = (String) event.data;
                    File target = new File((File) localDirBrowser.getInput(), text);
                    if (target.exists()) {
                        if (!MessageDialog.openConfirm(getShell(), "Overwriting confirmation", "Overwrite file " + target + "?")) {
                            return;
                        }
                    }

                    try {
                        FileOutputStream stream = new FileOutputStream(target);
                        if(ftp.retrieveFile(text, stream)) {
                            logMessage("File retrieved successfully.", true);
                            localDirBrowser.refresh();
                        }else{
                            logError("Failed to retrieve file: " + text);
                        }
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            public void dropAccept(DropTargetEvent event) {
            }
        });
        localDirBrowser.getControl().addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
                dropTarget.dispose();
            }
        });
    }
    protected MenuManager createMenuManager() {

        MenuManager bar = new MenuManager();
        MenuManager menuFile = new MenuManager("&File");
        menuFile.add(actionConnect);
        menuFile.add(actionDisconnect);
        menuFile.add(new Separator());
        menuFile.add(actionExit);
        MenuManager menuLocal = new MenuManager("&Local");
        menuLocal.add(actionBrowseLocalDir);
        menuLocal.add(actionUpLocalDir);
        MenuManager menuRemote = new MenuManager("&Remote");
        menuRemote.add(actionUpRemoteDir);
        MenuManager menuHelp = new MenuManager("&Help");
        menuHelp.add(actionDisplayAbout);
        bar.add(menuFile);
        bar.add(menuLocal);
        bar.add(menuRemote);
        bar.add(menuHelp);
        bar.updateAll(true);
        return bar;
    }
    public static void addAction(

        ToolBarManager manager,
        Action action,
        boolean displayText) {
        if (!displayText) {
            manager.add(action);
            return;
        } else {
            ActionContributionItem item = new ActionContributionItem(action);
            item.setMode(ActionContributionItem.MODE_FORCE_TEXT);
            manager.add(item);
        }
    }
    protected ToolBarManager createToolBarManager(int style) {

        ToolBarManager manager = super.createToolBarManager(style);
        addAction(manager, actionConnect, true);
        addAction(manager, actionDisconnect, true);
        manager.add(new Separator());
        addAction(manager, actionBrowseLocalDir, true);
        addAction(manager, actionUpLocalDir, true);
        manager.add(new Separator());
        addAction(manager, actionUpRemoteDir, true);
        manager.add(new Separator());
        addAction(manager, actionDisplayAbout, true);        
        addAction(manager, actionExit, true);
        manager.update(true);        

        return manager;
    }
    protected Control createContents(Composite parent) {
        Composite composite = new Composite(parent, SWT.NULL);
        composite.setLayout(new FillLayout());
        SashForm verticalForm = new SashForm(composite, SWT.VERTICAL);
        SashForm horizontalForm = new SashForm(verticalForm, SWT.HORIZONTAL);
        Composite compositeLocalDir = new Composite(horizontalForm, SWT.NULL);
        GridLayout gridLayout = new GridLayout();
        gridLayout.horizontalSpacing = 1;
        gridLayout.verticalSpacing = 1;
        compositeLocalDir.setLayout(gridLayout);
        Group compositeLocalDirTop = new Group(compositeLocalDir, SWT.NULL);
        compositeLocalDirTop.setText("Local");
        GridLayout gridLayout2 = new GridLayout(3, false);
        gridLayout2.marginHeight = 0;
        compositeLocalDirTop.setLayout(gridLayout2);
        compositeLocalDirTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        labelPathLocal = new Label(compositeLocalDirTop, SWT.NULL);
        labelPathLocal.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        labelPathLocal.setText("Path: ");
        Button buttonUpLocalDir = new Button(compositeLocalDirTop, SWT.PUSH);
        buttonUpLocalDir.setText(actionUpLocalDir.getText());
        buttonUpLocalDir.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                actionUpLocalDir.run();
            }
        });
        Button buttonBrowseLocalDir = new Button(compositeLocalDirTop, SWT.PUSH);
        buttonBrowseLocalDir.setText(actionBrowseLocalDir.getText());
        buttonBrowseLocalDir.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                actionBrowseLocalDir.run();
            }
        });
        Table table = new Table(compositeLocalDir, SWT.BORDER);
        TableColumn tcFile = new TableColumn(table, SWT.LEFT);
        tcFile.setText("Name");
        TableColumn tcSize = new TableColumn(table, SWT.NULL);
        tcSize.setText("Size");
        TableColumn tcDate = new TableColumn(table, SWT.NULL);
        tcDate.setText("Date");
        tcFile.setWidth(200);
        tcSize.setWidth(100);
        tcDate.setWidth(100);
        table.setHeaderVisible(true);
        table.setLayoutData(new GridData(GridData.FILL_BOTH));
        localDirBrowser = new LocalDirectoryBrowser(table);
        table.addListener(SWT.MouseDoubleClick, new Listener() {
            public void handleEvent(Event event) {
                IStructuredSelection selection = (IStructuredSelection) localDirBrowser.getSelection();
                File file = (File) selection.getFirstElement();
                if (file != null && file.isDirectory()) {
                    localDirBrowser.setInput(file);
                    labelPathLocal.setText("Path: " + file);
                }
            }
        });
        Composite compositeRemoteDir = new Composite(horizontalForm, SWT.NULL);
        gridLayout = new GridLayout();
        gridLayout.horizontalSpacing = 1;
        gridLayout.verticalSpacing = 1;
        compositeRemoteDir.setLayout(gridLayout);
        Group compositeRemoteDirTop = new Group(compositeRemoteDir, SWT.NULL);
        compositeRemoteDirTop.setText("Remote");
        gridLayout2 = new GridLayout(2, false);
        gridLayout2.marginHeight = 0;
        compositeRemoteDirTop.setLayout(gridLayout2);
        compositeRemoteDirTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        labelPathRemote = new Label(compositeRemoteDirTop, SWT.NULL);
        labelPathRemote.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        labelPathRemote.setText("Path: ");
        Button buttonUpRemoteDir = new Button(compositeRemoteDirTop, SWT.PUSH);
        buttonUpRemoteDir.setText(actionUpLocalDir.getText());
        buttonUpRemoteDir.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                actionUpRemoteDir.run();
            }
        });
        Table tableRemote = new Table(compositeRemoteDir, SWT.BORDER);
        TableColumn tcFileRemote = new TableColumn(tableRemote, SWT.LEFT);
        tcFileRemote.setText("Name");
        TableColumn tcSizeRemote = new TableColumn(tableRemote, SWT.NULL);
        tcSizeRemote.setText("Size");
        TableColumn tcDateRemote = new TableColumn(tableRemote, SWT.NULL);
        tcDateRemote.setText("Date");
        tcFileRemote.setWidth(200);
        tcSizeRemote.setWidth(100);
        tcDateRemote.setWidth(100);
        tableRemote.setHeaderVisible(true);
        tableRemote.setLayoutData(new GridData(GridData.FILL_BOTH));
        remoteDirBrowser = new RemoteDirectoryBrowser(tableRemote);
        tableRemote.addListener(SWT.MouseDoubleClick, new Listener() {
            public void handleEvent(Event event) {
                IStructuredSelection selection = (IStructuredSelection) remoteDirBrowser.getSelection();
                FTPFile file = (FTPFile) selection.getFirstElement();
                if (file != null && file.isDirectory()) {
                    try {
                        ftp.changeWorkingDirectory(file.getName());
                        labelPathRemote.setText("Path: " + ftp.printWorkingDirectory());
                        remoteDirBrowser.setInput(ftp.listFiles());
                    } catch (IOException e) {
                        logError(e.toString());
                    }
                }
            }
        });
        textLog =
            new StyledText(
                verticalForm,
                SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
        localDirBrowser.setInput(File.listRoots()[0]);
        labelPathLocal.setText("Path: " + File.listRoots()[0]);
        verticalForm.setWeights(new int[]{4, 1});
        dragNDropSupport();
        getToolBarControl().setBackground(new Color(getShell().getDisplay(), 230, 230, 230));
        getShell().setImage(new Image(getShell().getDisplay(), "C:/icons/ftp/ftp.gif"));
        getShell().setText("FTP Client v1.0");

        return composite;
    }
    private void logMessage(String message, boolean showInStatusBar) {
        StyleRange styleRange1 = new StyleRange();
        styleRange1.start = textLog.getCharCount();
        styleRange1.length = message.length();
        styleRange1.foreground = getShell().getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);
        styleRange1.fontStyle = SWT.NORMAL;
        textLog.append(message + "\r\n");
        textLog.setStyleRange(styleRange1);
        textLog.setSelection(textLog.getCharCount());
        if(showInStatusBar) {
            setStatus(message);
        }
    }
    private void logError(String message) {
        StyleRange styleRange1 = new StyleRange();
        styleRange1.start = textLog.getCharCount();
        styleRange1.length = message.length();
        styleRange1.foreground = getShell().getDisplay().getSystemColor(SWT.COLOR_DARK_RED);
        styleRange1.fontStyle = SWT.NORMAL;        
        textLog.append(message + "\r\n");
        textLog.setStyleRange(styleRange1);
        textLog.setSelection(textLog.getCharCount());
    }
    public static void main(String[] args) {
        ApplicationWindow window = new FTPWindow(null);
        window.setBlockOnOpen(true);
        window.open();
        Display.getCurrent().dispose();
    }
}

ConnectionDialog.java

复制代码 代码如下:

package swt_jface.demo13;
import java.io.File;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
class ConnectionInfo {
    public String host;
    public int port;
    public String password;
    public String username;

}
public class ConnectionDialog extends Dialog {

    private static final String DIALOG_SETTING_FILE = "ftp.connection.xml";
    private static final String KEY_HOST = "HOST";
    private static final String KEY_PORT = "PORT";
    private static final String KEY_USERNAME = "USER";
    private static final String KEY_PASSWORD = "PASSWORD";

    Text textHost;
    Text textPort;
    Text textUsername;
    Text textPassword;

    DialogSettings dialogSettings;
    ConnectionInfo connectionInfo;

    ConnectionDialog(FTPWindow window) {

        super(window.getShell());
        connectionInfo = null;

        dialogSettings = new DialogSettings("FTP");
        try {
            dialogSettings.load(DIALOG_SETTING_FILE);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    protected Control createDialogArea(Composite parent) {
        getShell().setText("Connection Settings");

        Composite composite = (Composite)super.createDialogArea(parent);
        composite.setLayout(new GridLayout(2, false));

        new Label(composite, SWT.NULL).setText("Host: ");
        textHost = new Text(composite, SWT.BORDER);
        textHost.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        new Label(composite, SWT.NULL).setText("Port: ");
        textPort = new Text(composite, SWT.BORDER);
        textPort.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        new Label(composite, SWT.NULL).setText("Username: ");
        textUsername = new Text(composite, SWT.BORDER);
        textUsername.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        new Label(composite, SWT.NULL).setText("Password: ");
        textPassword = new Text(composite, SWT.PASSWORD | SWT.BORDER);
        textPassword.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        try {
            textHost.setText(dialogSettings.get(KEY_HOST));
            textPort.setText(dialogSettings.getInt(KEY_PORT) + "");
            textUsername.setText(dialogSettings.get(KEY_USERNAME));
            textPassword.setText(dialogSettings.get(KEY_PASSWORD));
        }catch(Exception e) {
        }
        return composite;
    }
    public ConnectionInfo getConnectionInfo() {
        return connectionInfo;
    }
    protected void okPressed() {
        try {
            if(! new File(DIALOG_SETTING_FILE).exists()) {
                new File(DIALOG_SETTING_FILE).createNewFile();
            }
            dialogSettings.put(KEY_HOST, textHost.getText());
            dialogSettings.put(KEY_PORT, Integer.parseInt(textPort.getText().trim()));
            dialogSettings.put(KEY_USERNAME, textUsername.getText());
            dialogSettings.put(KEY_PASSWORD, textPassword.getText());
            dialogSettings.save(DIALOG_SETTING_FILE);
        }catch(Exception e) {
            e.printStackTrace();
        }
        connectionInfo = new ConnectionInfo();
        connectionInfo.host = textHost.getText();
        connectionInfo.port = Integer.parseInt(textPort.getText().trim());
        connectionInfo.username = textUsername.getText();
        connectionInfo.password = textPassword.getText();
        super.okPressed();
    }
}

FileIconUtil.java

复制代码 代码如下:

package swt_jface.demo13;
import java.io.File;
import org.apache.commons.net.ftp.FTPFile;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
public class FileIconUtil {

    static ImageRegistry imageRegistry;

    static Image iconFolder;
    static Image iconFile;

    static {
        iconFolder = new Image(Display.getCurrent(), "C:/icons/folder.gif");
        iconFile = new Image(Display.getCurrent(), "C:/icons/file.gif");
    }
    public static Image getIcon(File file) {
        if (file.isDirectory()) return iconFolder;
        int lastDotPos = file.getName().indexOf('.');
        if (lastDotPos == -1) return iconFile;
        Image image = getIcon(file.getName().substring(lastDotPos + 1));
        return image == null ? iconFile : image;
    }
    public static Image getIcon(FTPFile file) {
        if (file.isDirectory()) return iconFolder;
        int lastDotPos = file.getName().indexOf('.');
        if (lastDotPos == -1) return iconFile;
        Image image = getIcon(file.getName().substring(lastDotPos + 1));
        return image == null ? iconFile : image;
    }    
    private static Image getIcon(String extension) {
        if (imageRegistry == null) imageRegistry = new ImageRegistry();
        Image image = imageRegistry.get(extension);
        if (image != null) return image;
        Program program = Program.findProgram(extension);
        ImageData imageData = (program == null ? null : program.getImageData());
        if (imageData != null) {
            image = new Image(Display.getCurrent(), imageData);
            imageRegistry.put(extension, image);
        } else {
            image = iconFile;
        }
        return image;
    }    
}

LocalDirectoryBrowser.java

复制代码 代码如下:

package swt_jface.demo13;
import java.io.File;
import java.util.Date;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
public class LocalDirectoryBrowser extends TableViewer {
public LocalDirectoryBrowser(Table table) {
super(table);
init();
}

private void init() {
setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
File dir = (File)inputElement;
return dir.listFiles();
}
public void dispose() {
}
public void inputChanged(
Viewer viewer,
Object oldInput,
Object newInput) {
}
});

setLabelProvider(new ITableLabelProvider() {
public Image getColumnImage(Object element, int columnIndex) {
if(columnIndex == 0)
return FileIconUtil.getIcon((File)element);
return null;
}
public String getColumnText(Object element, int columnIndex) {
switch(columnIndex) {
case 0:
return ((File)element).getName();
case 1:
return ((File)element).length() + "";
case 2:
return new Date(((File)element).lastModified()).toString();
default:
return "";
}
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
});
}
}
package swt_jface.demo13;
import java.io.File;
import java.util.Date;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
public class LocalDirectoryBrowser extends TableViewer {
    public LocalDirectoryBrowser(Table table) {
        super(table);
        init();
    }

    private void init() {
        setContentProvider(new IStructuredContentProvider() {
            public Object[] getElements(Object inputElement) {
                File dir = (File)inputElement;
                return dir.listFiles();
            }
            public void dispose() {
            }
            public void inputChanged(
                Viewer viewer,
                Object oldInput,
                Object newInput) {
            }
        });

        setLabelProvider(new ITableLabelProvider() {
            public Image getColumnImage(Object element, int columnIndex) {
                if(columnIndex == 0)
                    return FileIconUtil.getIcon((File)element);
                return null;
            }
            public String getColumnText(Object element, int columnIndex) {
                switch(columnIndex) {
                    case 0:
                        return ((File)element).getName();
                    case 1:
                        return ((File)element).length() + "";
                    case 2:
                        return new Date(((File)element).lastModified()).toString();
                    default:
                        return "";        
                }
            }
            public void addListener(ILabelProviderListener listener) {
            }
            public void dispose() {
            }
            public boolean isLabelProperty(Object element, String property) {
                return false;
            }
            public void removeListener(ILabelProviderListener listener) {
            }
        });
    }
}

RemoteDirectoryBrowser.java

复制代码 代码如下:

package swt_jface.demo13;
import java.util.Calendar;
import org.apache.commons.net.ftp.FTPFile;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
public class RemoteDirectoryBrowser extends TableViewer {
public RemoteDirectoryBrowser(Table table) {
super(table);
init();
}

private void init() {
setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
FTPFile[] files = (FTPFile[])inputElement;
return files;
}
public void dispose() {
}
public void inputChanged(
Viewer viewer,
Object oldInput,
Object newInput) {
}
});

setLabelProvider(new ITableLabelProvider() {
public Image getColumnImage(Object element, int columnIndex) {
if(columnIndex == 0)
return FileIconUtil.getIcon((FTPFile)element);
return null;
}
public String getColumnText(Object element, int columnIndex) {
switch(columnIndex) {
case 0:
return ((FTPFile)element).getName();
case 1:
return ((FTPFile)element).getSize() + "";
case 2:
Calendar cal = ((FTPFile)element).getTimestamp();
return cal.get(Calendar.YEAR) + "-" +
cal.get(Calendar.MONTH) + "-" +
cal.get(Calendar.DAY_OF_MONTH) + " " +
cal.get(Calendar.HOUR_OF_DAY) + ":" +
cal.get(Calendar.MINUTE) + ":" +
cal.get(Calendar.SECOND);
default:
return "";
}
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
});
}

}

时间: 2024-09-27 15:34:44

SWT(JFace) FTP客户端实现_Java编程的相关文章

SWT(JFace)Group(分组显示)_Java编程

演示代码: 复制代码 代码如下: package swt_jface.demo9; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt

SWT(JFace)体验之GridLayout布局_Java编程

GridLayout布局 GridLayout 布局的功能非常强大,也是笔者常用的一种布局方式.GridLayout是网格式布局,它把父组件分成一个表格,默认情况下每个子组件占据一个单元格的空间,每个子组件按添加到父组件的顺序排列在表格中.GridLayout提供了很多的属性,可以灵活设置网格的信息.另外,GridLayout 布局提供了GridData类,子组件可以设置相应的GridData,例如 "dogPhoto.setLayoutData(gridData)",GridData

SWT(JFace)体验之ViewForm的使用_Java编程

代码如下: 复制代码 代码如下: package swt_jface.demo9; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.s

SWT/JFace核心编程目录(未完待续)

编程 <<SWT/Jface核心编程>>                          目录                     第一部分 从 Swing 到SWT 第1章        SWT/Jface 简介 1.1 最初的Swing工具包 1.2 什么是SWT/Jface 1.3 Swing 与 SWT 1.4 SWT/Jface 的包 1.5 如何安装 SWT Designer    1.5.1 下载    1.5.2 安装 SWT Designer    1.5.

SWT/Jface核心编程 一书目录

编程 <<SWT/Jface核心编程>>                          目录                     第一部分 从 Swing 到SWT 第1章        SWT/Jface 简介 1.1 最初的Swing工具包 1.2 什么是SWT/Jface 1.3 Swing 与 SWT 1.4 SWT/Jface 的包 1.5 如何安装 SWT Designer    1.5.1 下载    1.5.2 安装 SWT Designer    1.5.

Ftp客户端编程

关于Ftp协议:Ftp命令:Ftp返回值:Ftp编程结构:关于Ftp协议:关于Ftp协议,我想都大概了解,所以不做说明了.以下是RPC959的介绍:The objectives of FTP are 1) to promote sharing of files (computerprograms and/or data), 2) to encourage indirect or implicit (viaprograms) use of remote computers, 3) to shiel

SWT/JFace开发入门指南之搭建开发环境

写在前面的话 终于决定提起笔来写一篇关于swt和JFace编程的文章.在开始之前,我想先介绍一下你能够从将要出现的这一系列文章里得到什么,以及更重要的,你不能得到什么.我们的时间是如此之重要,以至于我们很难容忍把它浪费在自己不关心的事情上. 因为我刚开始写,所以到底这些文章会分成几次发布出来,也很难讲.但是我心里大体有这样一个提纲.也就是说,我打算介绍以下方面的内容: ·设定swt以及JFace的开发环境 ·swt的一些简单部件(widget)介绍 ·JFace的一些入门性介绍 ·swt和JFa

ftp客户端主动模式代码(c语言)

问题描述 ftp客户端主动模式代码(c语言) 跪求大神指点ftp主动模式如何用c编写,知道客户端和服务器端传输流程,但是写不出代码 解决方案 http://www.codeproject.com/Articles/8667/FTP-Client-Class 解决方案二: 只是缺少练习,找本unix网络编程的书看看,东西不多,只涉及到socket和多线程的就行了.

如何在Eclipse 3.6.2中安装swt/JFace

原文http://blog.csdn.net/nkliming/article/details/7790288 我之前一直想安装过swt,但是eclipse一直有问题,后来听说用java写的界面太难看了,所以一直也没再装过.最近做eclipse插件开发,没办法,又要再装swt了.按照下面的步骤,我成功完成了安装: 1.Eclipse:help->Install New Software ,右边有个add选项,界面如下: Name可以不输,location输入:http://dl.google.c