简体   繁体   English

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

[英]How can I copy a file and paste it to the clipboard using Java?

How can I copy a file and paste it to the clipboard using Java?如何使用 Java 复制文件并将其粘贴到剪贴板? My program can copy but it cannot paste.我的程序可以复制但不能粘贴。 It gives它给

Exception in thread "main" java.lang.ClassCastException:线程“主”java.lang.ClassCastException 中的异常:
java.util.Arrays$ArrayList cannot be cast to java.io.File java.util.Arrays$ArrayList 无法转换为 java.io.File

My code:我的代码:

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

Here is a full example taken from the DGuitar source code were I have removed the custom or specific Details based on your comment这是从 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) ;
    }

}

I can't detect any problem in the actual code.我无法在实际代码中检测到任何问题。 I guess, that the cast error occurs where you actually receive the content from the copy/paste operation, where you receive a file, wrapped in a list and may cast the list to File .我猜想,转换错误发生在您实际从复制/粘贴操作接收内容的地方,在那里您收到一个文件,包装在一个列表中,并且可能将该列表转换为File

Java cannot handle specific operating system-dependent operations like interfering clipboard etc. since it is a platform-independent language. Java 无法处理特定操作系统相关的操作,如干扰剪贴板等,因为它是一种平台无关的语言。 In JLS and Java API there are no methods for clipboard interference, however there are methods to handle file system operations declared in Java API as a part of JLS (java language specification) which is implemented in most of JVM implementations. In JLS and Java API there are no methods for clipboard interference, however there are methods to handle file system operations declared in Java API as a part of JLS (java language specification) which is implemented in most of JVM implementations.

To do such things, you should develop something in C/C++ (using Win32 API etc.) natively using JNI (Java Native Interface) or use off-the-shelf binaries and call them within your Java application.为此,您应该使用 JNI(Java 本地接口)在 C/C++(使用 Win32 API 等)中开发一些东西,或者使用现成的二进制文件并在您的 Java 应用程序中调用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM