I've used Java system clipboard to transfer text and image, but I wonder if it can copy and paste files ? If so where can I find some sample code ?
I found a similar question at : How can I copy a file and paste it to the clipboard using Java?
But nowhere in it can I find the word "clipboard", and I don't know how to use it.
The methods I use to copy image look like this :
public static void setClipboard(Image image) // This method writes a image to the system clipboard : from exampledepot.com
{
ImageSelection imgSel=new ImageSelection(image);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel,null);
}
public Image getImageFromClipboard() // Get an image off the system clipboard
{
Transferable transferable=Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable!=null&&transferable.isDataFlavorSupported(DataFlavor.imageFlavor))
{
try { return (Image)transferable.getTransferData(DataFlavor.imageFlavor); }
catch (UnsupportedFlavorException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
else System.err.println("getImageFromClipboard: That wasn't an image!");
return null;
}
How to modify the above code to transfer files ?
Essentially, yes. You need to remember that both the drag'n'drop API and the clipboard API use the same concept of a
Transferable
, which wraps the data intoDataFlavor
s, so you can transfer the data differently based on the flavor the target system would like to useGenerally, when transferring files, Java uses a
java.util.List
and aDataFlavor.javaFileListFlavor
. Unfourtantly, there's no nice "wrapper" class available for this, so you'll need to provide your own, for example...In my tests, I was able to place a
File
in theList
, wrap into aTransferable
, pass it to theClipboard
and was able to paste the file through the system (Windows Explorer)