我需要用java制作文件复印机。
我想知道如何确认操作系统文件系统中发生的事件以及如何控制它。
编写一个线程,使用以下代码连续执行剪贴板数据检查
// If a string is on the system clipboard, this method returns it;
// otherwise it returns null.
public static String getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String)t.getTransferData(DataFlavor.stringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
// This method writes a string to the system clipboard.
// otherwise it returns null.
public static void setClipboard(String str) {
StringSelection ss = new StringSelection(str);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
有关更多详细信息,请参阅以下课程
java.awt.datatransfer.Clipboard;
java.awt.datatransfer.ClipboardOwner;
java.awt.datatransfer.Transferable;
java.awt.datatransfer.StringSelection;
java.awt.datatransfer.DataFlavor;
下面是监听器示例
import java.awt.*;
import java.awt.datatransfer.*;
class BoardListener extends Thread implements ClipboardOwner {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
public void run() {
Transferable trans = sysClip.getContents(this);
regainOwnership(trans);
System.out.println("Listening to board...");
while(true) {}
}
public void lostOwnership(Clipboard c, Transferable t) {
Transferable contents = sysClip.getContents(this); //EXCEPTION
processContents(contents);
regainOwnership(contents);
}
void processContents(Transferable t) {
System.out.println("Processing: " + t);
}
void regainOwnership(Transferable t) {
sysClip.setContents(t, this);
}
public static void main(String[] args) {
BoardListener b = new BoardListener();
b.start();
}
}