如何使用Java复制文件并将其粘贴到剪贴板?

时间:2011-05-23 18:57:31

标签: java

如何使用Java复制文件并将其粘贴到剪贴板?我的程序可以复制,但无法粘贴。它给出了

  

线程“main”中的异常java.lang.ClassCastException:
  java.util.Arrays $ ArrayList无法强制转换为java.io.File

我的代码:

class FileTransferable implements Transferable {
    private final File file;

    public FileTransferable(File file) {
        this.file = file;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[] { DataFlavor.javaFileListFlavor };
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return DataFlavor.javaFileListFlavor.equals(flavor);
    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        final ArrayList<File> files = new ArrayList<File>();
        files.add(file);
        return files;
    }
}

3 个答案:

答案 0 :(得分:0)

我无法在实际代码中发现任何问题。我想,在您实际接收来自复制/粘贴操作的内容的地方会发生强制转换错误,您将收到一个文件,包含在列表中并且可以投射列表到File

答案 1 :(得分:0)

以下是从DGuitar源代码中获取的完整示例,我已根据您的评论删除了自定义或特定详细信息

/*
 * ADropTargetListener
 * Created on 20/04/2005
 *
 *
 */

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * The Drop action happens in this order: 1. dragEnter =
when the mouse enters
 * the component 2. dragOver = after the mouse has entered
but has not been
 * released 3. drop = when the mouse is released
 * 
 * @author Mauricio Gracia G
 */
public class ADropTargetListener implements DropTargetListener {
    /**
     * creates a DropTargetListener 
     */
    public ADropTargetListener() {

    }

    /**
     * overrides the DROP method.
     * 
     * @see java.awt.dnd.DropTargetListener#drop(java.awt.dnd.DropTargetDropEvent)
     */
    public void drop(DropTargetDropEvent dtde) {
        Transferable transfer;

        transfer = dtde.getTransferable();

        //we must accept the transfer to process it
        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

        importData(transfer);
    }
    /**
     * Imports the data of the Drop action
     * @param t the transferable object
     */

    public void importData(Transferable t) {
        if (canImport(t.getTransferDataFlavors())) {
            try {
                DataFlavor[] flavors = t.getTransferDataFlavors();
                for (int i = 0; i < flavors.length; i++) {
                    //       Drop from Windows
                    if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {

                        Object gtd ;

                        gtd = t.getTransferData(DataFlavor.javaFileListFlavor) ;
                        if (gtd instanceof List) {
                            @SuppressWarnings("unchecked")
                            List<File> fileList = (List<File>) gtd;

                                                        //YOUR CODE here to process the list of Files

                        }

                    }
                    //       Drop from GNOME or kde
                    // delimited by \n  (\r\n) on gnome
                    // will need to remove file:// at start
                    else if (DataFlavor.stringFlavor.equals(flavors[i])) {
                        if (t.getTransferData(DataFlavor.stringFlavor)
instanceof String) {
                            String path = (String) t
                                    .getTransferData(DataFlavor.stringFlavor);
                            List<File> fileList = convertStringsToFileList(path);
                            //YOUR CODE here to process the list of Files

                        }

                    }
                }
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();

            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }
    /**
     * converts Strings in certain format to a FileList 
     * @param filestr   the list of files in a single string
     * @return          a list of files
     */

    private ArrayList<File> convertStringsToFileList(String filestr) {
        ArrayList<File> files = new ArrayList<File>();
        String[] tokenizedFiles = filestr.split("\n");
        for (int i = 0; i < tokenizedFiles.length; i++) {
            String path = tokenizedFiles[i];
            if (path.startsWith("file://")) {
                if (path.endsWith("\r")) {
                    //appears to be the case for gnome but not kde
                    path = path.substring(7);
                    path = path.replaceAll("\r", "");

                    path = path.replaceAll("%20", " ");
                } else {
                    path = path.substring(7);
                }
            }
            files.add(new File(path));

        }
        return files;
    }
    /**
     * Determine if it can import certain flavor
     * 
     * @param flavors   an array of DataFlavors
     * @return true or not depending on the flavor
     */
    public boolean canImport(DataFlavor[] flavors) {
        for (int i = 0; i < flavors.length; i++) {
            if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                return true;
            } else if (DataFlavor.stringFlavor.equals(flavors[i])) {
                return true;
            }
        }
        return false;
    }


    /**
     * method that is called when the drag starts or enters the window
     * @param dtde a DropTargetDragEvent
     * 
     * @see java.awt.dnd.DropTargetListener#dragEnter(java.awt.dnd.DropTargetDragEvent)
     */
    public void dragEnter(DropTargetDragEvent dtde) {
        //DEBUG
        //System.out.println("dragEnter" + ":" + dtde) ;
    }

    /**
     * a method that is called when the DRAG is OVER ??
     * 
     * @see java.awt.dnd.DropTargetListener#dragOver(java.awt.dnd.DropTargetDragEvent)
     */

    public void dragOver(DropTargetDragEvent dtde) {
        //      DEBUG
        //System.out.println("dragOver" + ":" + dtde) ;
    }

    /**
     * when the drop action is changes this method is called
     * 
     * @see java.awt.dnd.DropTargetListener#dropActionChanged(java.awt.dnd.DropTargetDragEvent)
     */
    public void dropActionChanged(DropTargetDragEvent dtde) {
        //      DEBUG
        //System.out.println("dropActionChanged" + ":" + dtde) ;
    }

    /**
     * method called when the drag exits the window
     * 
     * @see java.awt.dnd.DropTargetListener#dragExit(java.awt.dnd.DropTargetEvent)
     */
    public void dragExit(DropTargetEvent dte) {
        //      DEBUG
        //System.out.println("dragExit" + ":" + dte) ;
    }

}

答案 2 :(得分:-6)

Java无法处理特定的操作系统相关操作,如干扰剪贴板等,因为它是一种独立于平台的语言。在JLS和Java API中,没有剪贴板干扰的方法,但是有一些方法可以处理在Java API中声明的文件系统操作,作为JLS(Java语言规范)的一部分,它在大多数JVM实现中实现。

要做这些事情,你应该使用JNI(Java Native Interface)本地使用C / C ++(使用Win32 API等)开发一些东西,或者使用现成的二进制文件并在Java应用程序中调用它们。