Category → CS

Stash

rustc -C prefer-dynamic
.meter-text { white-space: pre-wrap; }
launchctl stop com.apple.pboard
launchctl start com.apple.pboard
# requires ImageMagick
function img() {
    identify -format '<img src="%f" width="%w" height="%h" />' $1
}

Java Clipboards and Data Transfer

(Ported from betaveros.stash. Wow, I get syntax highlighting and footnotes! Probably years out of date though. I probably wrote this somewhere in 2012–2014, but am editing this parenthetical in 2021.)

A quick brief guide. At least, that’s how I planned it.

A lot of stuff is in the package java.awt.datatransfer. Class Toolkit is in java.awt.

Some basic classes. The class Clipboard is a clipboard, obviously. Its content is/will be an instance of the class Transferable. Some content can be read as different types of objects depending on what you want; to choose which type you use an instance of DataFlavor. It provides three basic ones: DataFlavor.imageFlavor, DataFlavor.javaFileListFlavor, and DataFlavor.stringFlavor.

Okay, now step by step. This is the low-level method.

  1. Get the default clipboard with Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  2. Get a transferable with Transferable content = clipboard.getContents(null); 1
  3. Check if content can be read as the kind of object you want with (content != null) && content.isDataFlavorSupported(someFlavor)
  4. If it does, get the object with content.getTransferData(someFlavor) 2.

If you just want a quick-and-dirty function:

static String getClipboard()
        throws java.awt.datatransfer.UnsupportedFlavorException, IOException {
    return (String) java.awt.Toolkit.getDefaultToolkit()
        .getSystemClipboard()
        .getData(java.awt.datatransfer.DataFlavor.stringFlavor);
}