/* * Copyright 2008 (C) Jeffrey Palm * * This code is licensed under the GPL. */ import java.awt.*; import java.awt.datatransfer.*; import java.io.*; /** * Copies the contents of all the input files to the clipboard. * * @author Jeffrey Palm */ public class CopyToClipboard { public static void main(String[] args) throws IOException { new CopyToClipboard().realMain(args); } void realMain(String[] args) throws IOException { // // A little error checking on the input // if (args.length == 0) { System.err.println("Usage: java " + getClass().getName() + " +"); System.err.println("where each file's content will be copied to the clipbard."); return; } // // Copy all the files to the clipboard // final TextTransfer tt = new TextTransfer(); StringBuffer buf = new StringBuffer(); for (String arg : args) { BufferedReader in = new BufferedReader(new FileReader(arg)); String line; while ((line = in.readLine()) != null) { buf.append(line); buf.append("\n"); } in.close(); } String s = buf.toString(); System.err.println("Copying " + s.length() + " chars to the clipboard"); tt.setClipboardContents(s); System.err.println("Copied " + s.length() + " chars to the clipboard"); } /** * Taken from: http://www.javapractices.com/Topic82.cjp */ final static class TextTransfer implements ClipboardOwner { /** * Empty implementation of the ClipboardOwner interface. */ public void lostOwnership( Clipboard aClipboard, Transferable aContents) { //do nothing } /** * Place a String on the clipboard, and make this class the * owner of the Clipboard's contents. */ public void setClipboardContents( String aString ){ StringSelection stringSelection = new StringSelection( aString ); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, this ); } /** * Get the String residing on the clipboard. * * @return any text found on the Clipboard; if none found, return an * empty String. */ public String getClipboardContents() { String result = ""; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //odd: the Object param of getContents is not currently used Transferable contents = clipboard.getContents(null); boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor) ; if ( hasTransferableText ) { try { result = (String)contents.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException ex){ //highly unlikely since we are using a standard DataFlavor System.out.println(ex); ex.printStackTrace(); } catch (IOException ex) { System.out.println(ex); ex.printStackTrace(); } } return result; } } }