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.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Eclipse and tagged . Bookmark the permalink.

5 Responses to SWT – Putting a file into the clipboard

  1. 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

Comments are closed.