我需要在java中创建一个文件复制器。
我想知道如何确认操作系统文件系统中发生的事件以及如何控制它。
答案 0 :(得分:1)
使用以下代码编写一个连续执行剪贴板数据检查的线程
// 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();
}
}