SWT(JFace) FTP客户端实现

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

}

(0)

相关推荐

  • SWT(JFace) FTP客户端实现

    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 or

  • SWT(JFace)体验之GridLayout布局

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

  • python实现简单ftp客户端的方法

    本文实例讲述了python实现简单ftp客户端的方法.分享给大家供大家参考.具体实现方法如下: #!/usr/bin/python # -*- coding: utf-8 -*- import ftplib import os import socket HOST = 'ftp.mozilla.org' DIRN = 'pub/mozilla.org/webtools' FILE = 'bugzilla-3.6.9-to-3.6.10-nodocs.diff.gz' def writedata(

  • Python使用ftplib实现简易FTP客户端的方法

    本文实例讲述了Python使用ftplib实现简易FTP客户端的方法.分享给大家供大家参考.具体实现方法如下: #!/usr/bin/python #-*- coding:utf-8 -*- from ftplib import FTP #加载ftp模块 ftp=FTP() #设置变量 ftp.set_debuglevel(2) #打开调试级别2,显示详细信息 ftp.connect("IP","port") #连接的ftp sever和端口 ftp.login(&

  • C#实现FTP客户端的案例

    本文是利用C# 实现FTP客户端的小例子,主要实现上传,下载,删除等功能,以供学习分享使用. 思路: 通过读取FTP站点的目录信息,列出对应的文件及文件夹. 双击目录,则显示子目录,如果是文件,则点击右键,进行下载和删除操作. 通过读取本地电脑的目录,以树状结构展示,选择本地文件,右键进行上传操作. 涉及知识点: FtpWebRequest[实现文件传输协议 (FTP) 客户端] / FtpWebResponse[封装文件传输协议 (FTP) 服务器对请求的响应]Ftp的操作主要集中在两个类中.

  • C# 实现FTP客户端的小例子

    本文是利用C# 实现FTP客户端的小例子,主要实现上传,下载,删除等功能,以供学习分享使用. 思路: 通过读取FTP站点的目录信息,列出对应的文件及文件夹. 双击目录,则显示子目录,如果是文件,则点击右键,进行下载和删除操作. 通过读取本地电脑的目录,以树状结构展示,选择本地文件,右键进行上传操作. 涉及知识点: FtpWebRequest[实现文件传输协议 (FTP) 客户端] / FtpWebResponse[封装文件传输协议 (FTP) 服务器对请求的响应]Ftp的操作主要集中在两个类中.

  • python中的socket实现ftp客户端和服务器收发文件及md5加密文件

    客户端向服务器发送一个请求,请求内容是一个文件名,服务器在查找自己这边有没有这个文件,如果有的话就发送给客户端 1.客户端 生成socket对象 建立连接 输入想要接收的文件 将输入的文件名发送给服务器 接收服务器发回的关于即将要发送来的文件的大小 发送一条信息给服务器告诉它准备好接收了 接收文件数据 打印全部接收的提示信息 client具体实现的代码如下: # Author: Mr.Xue # 2019.10.29 # socket_ftp_client.py import socket im

  • C++实现简单FTP客户端软件开发

    本文实例为大家分享了C++实现简单FTP客户端软件开发的具体实现代码,供大家参考,具体内容如下 题目 简单FTP客户端软件开发(100分)网络环境中的一项基本应用就是将文件从一台计算机中复制到另一台可能相距很远的计算机中.而文件传送协议FTP是因特网上使用得最广泛的文件传送协议.FTP使用客户服务器方式. 设计要求: 1)以命令行形式运行2)该FTP客户端程序具有以下基本功能:能完成FTP链接的打开和关闭操作:能执行文件的上传和下载:能完成目录的创建.删除等有关操作.3)设计中加入新的功能:登录

  • SWT(JFace) Wizard(Eclipse插件编程必备)

    演示代码如下: HotelReservation.java 复制代码 代码如下: package swt_jface.demo12; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclips

  • SWT(JFace) 打印功能

    演示代码如下: 复制代码 代码如下: package swt_jface.demo11; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.printing.PrintDialog; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.printing.PrinterData; import org.eclipse.swt.widgets.Display

随机推荐