SWT – Putting a file into the clipboard
I recently got the question how you can put a file into the system clipboard.
SWT makes this trivial:
package de.vogella.desktop.clipboard;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Display;
/**
* Utility class for putting files into the system clipboard
*
* @author Lars Vogel
*/
public final class CopyFileToClipboard {
private CopyFileToClipboard() {
// Utility class, prevent instantiation
}
/**
* Copy a file into the clipboard
* Assumes the file exists -> no additional check
* @param fileName - includes the path
*/
public static void copytoClipboard(String fileName) {
Display display = Display.getCurrent();
Clipboard clipboard = new Clipboard(display);
String[] data = { fileName };
clipboard.setContents(new Object[] { data },
new Transfer[] { FileTransfer.getInstance() });
clipboard.dispose();
}
}
Afer calling the method with a correct filename you should be able to paste the file, e.g. Strg+V into your system file browser.
September 4th, 2009 at 2:27 am
You should dispose that Clipboard when you’re done with it actually.
“Constructs a new instance of this class. Creating an instance of a Clipboard may cause system resources to be allocated depending on the platform. It is therefore mandatory that the Clipboard instance be disposed when no longer required.”
http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/dnd/Clipboard.html#Clipboard%28org.eclipse.swt.widgets.Display%29
September 4th, 2009 at 7:56 am
Thank you Remy; I adjusted the coding.
September 23rd, 2009 at 1:02 pm
Hey,
I tried the code above, however it only works after I close the Java Application. In other words, I run the Java Application and one of these methods copy an excel file to Clipboard using this exactly code, however when I right click on the desktop the paste option is not enabled. When I close the java application, then it is possible to paste and it does perfectly.
Do you have idea why is this happening?
September 23rd, 2009 at 1:22 pm
@Tomas: The Snippet works fine for me under Windows. Which platform are you on?
September 23rd, 2009 at 2:08 pm
Hey Lars,
Windows as well. I just solved the problem, now the I copy the file to the clipboard inside a new thread and this seems that the issue was solved.
Thank you