SWT - Putting a file into the clipboard

less than 1 minute read

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.

Updated: