get Buffer text from Clipboard - Java Native OS

Java examples for Native OS:Clipboard

Description

get Buffer text from Clipboard

Demo Code


//package com.java2s;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getBuffer());
    }//  w  w w .  ja va 2s . co m

    public static String getBuffer() {
        Clipboard systemClipboard = Toolkit.getDefaultToolkit()
                .getSystemClipboard();
        DataFlavor[] df = systemClipboard.getAvailableDataFlavors();
        for (DataFlavor dataFlavor : df) {
            Class<?> clazz = dataFlavor.getRepresentationClass();
            if (clazz == java.lang.String.class
                    && dataFlavor.getMimeType().contains(
                            "text/plain; class=java.lang.String")) {
                String str = null;
                try {
                    str = (String) systemClipboard.getData(dataFlavor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return str;
            }
        }
        return null;
    }
}

Related Tutorials