Is it possible to know whether the copied content in clipboard is mp3 file using awt.Toolkit and Clipboard in java

十年热恋 提交于 2019-12-02 23:48:35

问题


I am trying to write a code which runs at background and monitors the copy actions for copying a .mp3 file or a folder containing a .mp3 file

{

            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();

        if (cb.isDataFlavorAvailable(DataFlavor.javaFileListFlavor))
         {
               try {
                String name = ""+cb.getData(DataFlavor.javaFileListFlavor);
             boolean found = false;
                 if (name.toLowerCase().endsWith(".mp3]"))
                     {
                                System.out.println("Is MP3");
                                found = true;
                             }


                 if (!found)
               {
                        System.out.println("Is not MP3");
                   }

                    }

           catch(UnsupportedFlavorException ex)
             {
                ex.printStackTrace();
                 }
           catch(IOException ex)
             {
                ex.printStackTrace();
                 }
         }

    }

回答1:


Basically, yes. You need to check the Clipboard contents to see if it supports the DataFlavor.javaFileListFlavor DataFlavor. If it does, you need to iterate over the contents (which is java.util.List of Files) and make a determination of the content.

The following only checks to see if the files are .mp3 files (by checking the name extension), but it wouldn't be hard to check for isDirectory and do a recursive check of the directory...

Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
if (cb.isDataFlavorAvailable(DataFlavor.javaFileListFlavor)) {
    try {
        List files = (List) cb.getData(DataFlavor.javaFileListFlavor);
        boolean found = false;
        for (Object o : files) {
            if (o instanceof File) {
                File f = (File) o;
                if (f.getName().toLowerCase().endsWith(".mp3")) {
                    System.out.println("I haz MP3");
                    found = true;
                }
            }
        }
        if (!found) {
            System.out.println("I notz haz MP3");
        }
    } catch (UnsupportedFlavorException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}



回答2:


My suggestion is: http://msdn.microsoft.com/en-us/library/ff468802(v=vs.85).aspx

Using native windows C function and user JNA(Java native access library) to complete your requirement. JNA: https://github.com/twall/jna



来源:https://stackoverflow.com/questions/22602950/is-it-possible-to-know-whether-the-copied-content-in-clipboard-is-mp3-file-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!