我想创建一个可以访问剪贴板的java程序,用于执行剪切,复制和粘贴等功能。如果有人愿意帮我提供示例代码,那将会非常有帮助... 谢谢!
答案 0 :(得分:4)
/**
* 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*/);
答案 1 :(得分:1)
以下是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);
}