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.

Tags:
Filed under: Eclipse

Comments

  1. Remy Chi Jian Suen Says:

    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

  2. Lars Vogel Says:

    Thank you Remy; I adjusted the coding.

  3. Tomas Trindade Says:

    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?

  4. Lars Vogel Says:

    @Tomas: The Snippet works fine for me under Windows. Which platform are you on?

  5. Tomas Trindade Says:

    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


Switch to our mobile site