2
我想要一個Java程序,可以訪問剪貼板執行功能,如剪切,複製和粘貼。如果有人願意幫我提供一個示例代碼,這將非常有幫助... 謝謝!如何做在Java剪切複製粘貼
我想要一個Java程序,可以訪問剪貼板執行功能,如剪切,複製和粘貼。如果有人願意幫我提供一個示例代碼,這將非常有幫助... 謝謝!如何做在Java剪切複製粘貼
這裏是字符串複製爲JDK 7+(JavaFX的2)的一個工作示例:
public String pasteFromClipboard() {
return Clipboard.getSystemClipboard().getString();
}
public void copyToClipboard(String text) {
HashMap<DataFormat, Object> map = new HashMap<DataFormat, Object>();
map.put(DataFormat.PLAIN_TEXT, text);
Clipboard.getSystemClipboard().setContent(map);
}
/**
* get string from Clipboard
*/
public static String getSysClipboardText() {
String ret = "";
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable clipTf = sysClip.getContents(null);
if (clipTf != null) {
if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
ret = (String) clipTf
.getTransferData(DataFlavor.stringFlavor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return ret;
}
/**
* put string into Clipboard
*/
public static void setSysClipboardText(String writeMe) {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(writeMe);
clip.setContents(tText, null);
}
/**
* get image from Clipboard
*/
public static Image getImageFromClipboard() throws Exception {
Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable cc = sysc.getContents(null);
if (cc == null)
return null;
else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
return (Image) cc.getTransferData(DataFlavor.imageFlavor);
return null;
}
/**
* put iamge into Clipboard
*/
public static void setClipboardImage(final Image image) {
Transferable trans = new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor))
return image;
throw new UnsupportedFlavorException(flavor);
}
};
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
null);
}
,如果你要處理的文件或文件夾,你可以嘗試
copyFile(srcPath, destDir, true/**overwriteExistFile*/);
copyDirectory(srcPath, destDir, true/**overwriteExistDir*/);
使用的java.awt.datatransfer包,做R&d –
http://www.javaworld.com/javatips/jw- javatip61.html –
http://docs.oracle.com/javase/7/docs/api/java/awt/datatransfer/Clipboard.html – AsG