Reads a string from system clipboard. - Java Native OS

Java examples for Native OS:Clipboard

Description

Reads a string from system clipboard.

Demo Code

// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
//package com.java2s;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;

import java.awt.datatransfer.Transferable;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getStringFromClipboard());
    }/* w w w . ja v  a  2s. c o m*/

    /**
     * Reads a string from system clipboard.
     */
    public static String getStringFromClipboard() {
        Clipboard clipboard = Toolkit.getDefaultToolkit()
                .getSystemClipboard();
        Transferable paste = clipboard.getContents(null);
        if (paste == null) {
            return null;
        }
        try {
            return (String) paste.getTransferData(DataFlavor.stringFlavor);
        } catch (Exception ex) {
            return null;
        }
    }
}

Related Tutorials