Wednesday, November 16, 2016

Access Clipboard content using Java

You can access the text or images in clipboard using Java.

Software Features:

1) On copying any text, it gets placed in clipboard. This program can retrieve the text from clipboard
2) On using print screen, the image gets stored in clipboard. This program can retrieve the image from clipboard
3) When you copy file in windows, the file path get stored in clipboard. This program can retrieve the file path from clipboard and then copy the file to current directory.

Language:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/Clipboard/AccessClipboard

Terms Used:
Current directory: Current directory in this post refer to the path from where you are running the program

Program:

Main method:
      public static void main(String[] args) throws Exception {  
           Toolkit toolkit = Toolkit.getDefaultToolkit();  
           Clipboard clipboard = toolkit.getSystemClipboard();  
           if (clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor))   
           {  
           getCopiedFile(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))   
           {  
           getText(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor))   
           {  
           getImageFromClipboard(clipboard);  
           }  
      }  


How it works:
1) We access the clipboard object by using Toolkit.getDefaultToolkit().getSystemClipboard()
2) Now we check what data is present in clipboard by calling isDataFlavorAvailable(DataFlavor)
3) If copied image is present in clipboard then clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor) will return true else false. If true, we call getCopiedFile(clipboard) which shows the name of all files which user copied and saves the copied file at current directory.
4) If text is present in clipboard then clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) will return true else false. If true then we call getText(clipboard) which retrieves the text from clipboard and prints the same
5) If print screen image is present in clipboard then clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor) return true else false. If true, we call getImageFromClipboard(clipboard) which retrieves the print screen image and saves it to your current directory

getCopiedFile method:
      public static Object getCopiedFile(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           Object result = clipboard.getData(DataFlavor.javaFileListFlavor);  
     List files = (List) result;  
     for (int i = 0; i < files.size(); i++) {  
       File file = (File) files.get(i);  
       File destFile=new File(file.getName());  
       copyFileUsingStream(file, destFile);  
       System.out.println("Copied file "+file.getName()+" to "+destFile.getAbsolutePath());  
     }  
           return result;  
      }  


How it works:
1) This method is called to retrieve the copied image and save those.
2) To explain we will take an example. Assume user copied c:\1.jpg & c:\2.jpg
3) Clipboard will now have 2 entries which is c:\1.jpg and c:\2.jpg
4) clipboard.getData(DataFlavor.javaFileListFlavor) will retrieve both the entries from clipboard in form of List<File>
5) We iterate through each entry of List<File>
6) For each File found we will copy it to the current directory. So in 1st iteration we will copy 1.jpg to the current directory & in next iteration it would copy 2.jpg to current directory.

getImageFromClipboard method:
      public static Image getImageFromClipboard(Clipboard clipboard)  
                throws Exception  
                {  
                 Transferable transferable = clipboard.getContents(null);  
                 Image img=(Image) transferable.getTransferData(DataFlavor.imageFlavor);  
                     if(img!=null)  
                     {  
                          counter++;  
                          BufferedImage buffered = (BufferedImage) img;  
                          ImageIO.write(buffered, "jpg", new File("copiedFile"+counter+".jpg"));  
                          System.out.println("Saved the clipboard image as copiedFile"+counter+".jpg");  
                     }  
                     return img;  
                }  


How it works:
1) Assume user press print screen on a page. Now the print screen image gets saved to clipboard.
2) clipboard.getContents(null).getTransferData(DataFlavor.imageFlavor) gets the image from the clipboard
3) We cast the Image to BufferedImage and then use ImageIO to write the image to a file which gets saved in current directory

getText method:
      public static String getText(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           String result = (String) clipboard.getData(DataFlavor.stringFlavor);  
           System.out.println("String from Clipboard:" + result);  
           return result;  
      }  


How it works:
1) Assume user copies a text and now the text is present in clipboard
2) clipboard.getData(DataFlavor.stringFlavor) gets the text from the clipboard and then we print it

copyFileUsingStream method:
      private static void copyFileUsingStream(File source, File dest) throws IOException {  
        InputStream is = null;  
        OutputStream os = null;  
        try {  
          is = new FileInputStream(source);  
          os = new FileOutputStream(dest);  
          byte[] buffer = new byte[1024];  
          int length;  
          while ((length = is.read(buffer)) > 0) {  
            os.write(buffer, 0, length);  
          }  
        } finally {  
          is.close();  
          os.close();  
        }  
      }  


How it works:
1) This method copies files from source to destination.

Sample Output:
Copied file 2.png to C:\Users\anurag\workspace\cooltrickshome\2.png
Copied file oranges-1117628_640.jpg to C:\Users\anurag\workspace\cooltrickshome\oranges-1117628_640.jpg

Full Program:
 package com.cooltrickshome;  
 import java.awt.Image;  
 import java.awt.Toolkit;  
 import java.awt.datatransfer.Clipboard;  
 import java.awt.datatransfer.DataFlavor;  
 import java.awt.datatransfer.Transferable;  
 import java.awt.datatransfer.UnsupportedFlavorException;  
 import java.awt.image.BufferedImage;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.OutputStream;  
 import java.util.ArrayList;  
 import java.util.List;  
 import javax.imageio.ImageIO;  
 public class AccessClipboard {  
      /**  
       * @param args  
       * @throws Exception   
       */  
      static int counter=0;  
      public static void main(String[] args) throws Exception {  
           Toolkit toolkit = Toolkit.getDefaultToolkit();  
           Clipboard clipboard = toolkit.getSystemClipboard();  
           if (clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor))   
           {  
           getCopiedFile(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))   
           {  
           getText(clipboard);  
           }  
           if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor))   
           {  
           getImageFromClipboard(clipboard);  
           }  
      }  
      public static Object getCopiedFile(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           Object result = clipboard.getData(DataFlavor.javaFileListFlavor);  
     List files = (List) result;  
     for (int i = 0; i < files.size(); i++) {  
       File file = (File) files.get(i);  
       File destFile=new File(file.getName());  
       copyFileUsingStream(file, destFile);  
       System.out.println("Copied file "+file.getName()+" to "+destFile.getAbsolutePath());  
     }  
           return result;  
      }  
      public static Image getImageFromClipboard(Clipboard clipboard)  
                throws Exception  
                {  
                 Transferable transferable = clipboard.getContents(null);  
                 Image img=(Image) transferable.getTransferData(DataFlavor.imageFlavor);  
                     if(img!=null)  
                     {  
                          counter++;  
                          BufferedImage buffered = (BufferedImage) img;  
                          ImageIO.write(buffered, "jpg", new File("copiedFile"+counter+".jpg"));  
                          System.out.println("Saved the clipboard image as copiedFile"+counter+".jpg");  
                     }  
                     return img;  
                }  
      public static String getText(Clipboard clipboard) throws UnsupportedFlavorException, IOException  
      {  
           String result = (String) clipboard.getData(DataFlavor.stringFlavor);  
           System.out.println("String from Clipboard:" + result);  
           return result;  
      }  
      private static void copyFileUsingStream(File source, File dest) throws IOException {  
        InputStream is = null;  
        OutputStream os = null;  
        try {  
          is = new FileInputStream(source);  
          os = new FileOutputStream(dest);  
          byte[] buffer = new byte[1024];  
          int length;  
          while ((length = is.read(buffer)) > 0) {  
            os.write(buffer, 0, length);  
          }  
        } finally {  
          is.close();  
          os.close();  
        }  
      }  
 }  

Hope it helps :)

1 comment:

  1. When you are explaining this much about PASTING, you should have explained COPYING as well

    ReplyDelete