package com.company.app.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; @RestController public class DemoController { @GetMapping(value = "/get",produces = {"application/json; charset=UTF-8"}) public String get() { return getClipboardString(); } @GetMapping("/set") public String get(String value) { setClipboardString(value); return "ok:"+getClipboardString(); } /** * 从剪贴板中获取文本(粘贴) */ public static String getClipboardString() { // 获取系统剪贴板 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // 获取剪贴板中的内容 Transferable trans = clipboard.getContents(null); if (trans != null) { // 判断剪贴板中的内容是否支持文本 if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { // 获取剪贴板中的文本内容 String text = (String) trans.getTransferData(DataFlavor.stringFlavor); return text; } catch (Exception e) { e.printStackTrace(); } } } return null; } /** * 把文本设置到剪贴板(复制) */ public static void setClipboardString(String text) { // 获取系统剪贴板 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // 封装文本内容 Transferable trans = new StringSelection(text); // 把文本内容设置到系统剪贴板 clipboard.setContents(trans, null); } public static void main(String[] args) { String clipboardString = getClipboardString(); System.out.println(clipboardString); } }
package com.company.app; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; @SpringBootApplication public class Application { public static void main(String[] args) { // SpringApplication.run(Application.class, args); SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class); builder.headless(false).web(WebApplicationType.SERVLET).run(args); } }
标签:功能,同步,String,粘贴板,剪贴板,springframework,import,trans,public From: https://www.cnblogs.com/zhangshiwen/p/17070294.html