Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Main {
    public static void main(String[] args) {
        System.out.println(getClipboardData());
    }

    public static String getClipboardData() {
        String result = "";
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        Transferable contents = clipboard.getContents(null);
        DataFlavor dfRTF = new DataFlavor("text/rtf", "Rich Formatted Text");
        DataFlavor dfTxt = DataFlavor.stringFlavor;

        boolean hasTransferableRTFText = (contents != null) && contents.isDataFlavorSupported(dfRTF);

        boolean hasTransferableTxtText = (contents != null) && contents.isDataFlavorSupported(dfTxt);

        if (hasTransferableRTFText) {
            try {
                result = streamToString((InputStream) contents.getTransferData(dfRTF));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (hasTransferableTxtText) {
            try {
                result = (String) contents.getTransferData(dfTxt);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    private static String streamToString(InputStream transferData) {
        return slurp(transferData, 1024);
    }

    public static String slurp(final InputStream is, final int bufferSize) {
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        try {
            final Reader in = new InputStreamReader(is, "UTF-8");
            try {
                for (;;) {
                    int rsz = in.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
            } finally {
                in.close();
            }
        } catch (Exception ex) {
        }
        return out.toString();
    }

}