Search code examples
javaclipboarddata

How to copy/paste 'int' content from webpage


I want to copy/paste an int from a website, I know it's a very good way, even a non-proper one but i didn't find better

With Java.awt.Robot I go at the good position on page, make 2 clics to select the content, and then make a ctrl+C to add it to the clipboard

But then I have to get back the value which is an int

public static String getAsText() {
        String clipText = "";
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable contents = clipboard.getContents(null);
        if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                clipText = (String) contents.getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException ex) {
                Logger.getLogger(ClipboardTransfert.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ClipboardTransfert.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return clipText;
    }    

This works for String, but not int. I tried with :

  • DataFlavor intFlavor = new DataFlavor(int.class, "Integer"); but Exception at isDataFlavorSupported

  • Change type method to int, also to clipText variable, but not working

  • usual casting methods but not working, it prints the String (to be sure => if i do theString + 1, I get : theString1)

So how to ?


Solution

  • I might be misunderstanding your problem, but can't you just parse it? Like this:

    int clipboardContent = Integer.parseInt(contents.getTransferData(DataFlavor.stringFlavor));