Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cut a file to the clipboard in Java?

Tags:

java

clipboard

I am using this code in a Java Swing application to copy files to the clipboard:

final List<File> files = new ArrayList<File>();
// ... code to fill list omitted ... //

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
    new Transferable() {
        @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 {
            return files;
        }
    }, null
);

It works, in that I can go to Windows Explorer and Ctrl+V and the files turn up (hopefully it works in other OSes, though not tested). I'd like to implement cut also but I don't know how to let the system know that that's what the action is, or alternatively, how to get feedback for each successfully copied file so I can delete it from its original location manually.

If this isn't impossible, any suggestions on how I should handle this? I'd like to be able to cut & paste within the application too (separately to exchanging files with the OS explorer).

like image 582
Boann Avatar asked Jun 14 '12 08:06

Boann


People also ask

How do I get to clipboard in Java?

The system clipboard can be accessed by calling Toolkit. getDefaultToolkit(). getSystemClipboard(). You can use this technique if you are interested in exchanging data between your application and other applications (Java or non-Java) running on the system.

What is System clipboard in Java?

A class that implements a mechanism to transfer data using cut/copy/paste operations. FlavorListener s may be registered on an instance of the Clipboard class to be notified about changes to the set of DataFlavor s available on this clipboard (see addFlavorListener(java. awt.

How to get copied data from clipboard in Java?

The setContents() method is used to set contents to Clipboard, like cut-copy operations, and the getContents() method is used to retrieve the content from Clipboard, like the paste operation. A data package to be set in the Clipboard must be wrapped in a Transferable object.


1 Answers

There is another post where people discuss the lack of a possibility to cut files:

Cutting files into the clipboard with SWT

If you really need it you could go the ugly way and check if there is a way to do this via JNI-calls, but then you have to do that for all platforms that you want to support...

like image 86
Bernhard Avatar answered Oct 21 '22 10:10

Bernhard