Created
January 22, 2025 07:36
-
-
Save gwenn/274846cca8d54f57a61d2b279b5e7766 to your computer and use it in GitHub Desktop.
Clipboards
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Toolkit; | |
import java.awt.datatransfer.Clipboard; | |
import java.awt.datatransfer.DataFlavor; | |
import java.awt.datatransfer.StringSelection; | |
import java.awt.datatransfer.Transferable; | |
import java.io.IOException; | |
import java.io.Reader; | |
import java.util.List; | |
import com.google.common.io.CharStreams; | |
import org.apache.commons.lang3.function.FailableFunction; | |
import scenarisk.ScenariskException; | |
import javax.annotation.Nullable; | |
public class Clipboards { | |
public static String getClipboardContents() throws ScenariskException { | |
return getContents(CharStreams::toString); | |
} | |
public static List<String> getClipboardLines() throws ScenariskException { | |
return getContents(CharStreams::readLines); | |
} | |
@Nullable | |
private static <T> T getContents(FailableFunction<Reader, T, IOException> extract) throws ScenariskException { | |
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); | |
if (t == null) { | |
return null; | |
} | |
try { | |
DataFlavor dataFlavor = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors()); | |
if (dataFlavor == null) { | |
return null; | |
} | |
try (Reader reader = dataFlavor.getReaderForText(t)) { | |
return extract.apply(reader); | |
} | |
} catch (Exception e) { | |
throw new ScenariskException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment