繁体   English   中英

从Java查询Mac OS X Spotlight

[英]Query Mac OS X Spotlight from Java

相关:

从Java查询Windows搜索

但这次是使用OSX的焦点

我想从Java使用OSX聚光灯服务。 有API可用吗?

我不知道有没有Spotlight的Java API(我不认为它已被添加到桥上已停用的Cocoa-Java桥开发中)。 但是,有一个适用于Spotlight的过程C API ,您可以使用JNI进行包装。

找到了一些包装mdfind命令行的代码 ,对我来说很好用:

import java.io.*;
import java.util.*;


/**
 * This class performs filesystem searches using the Spotlight facility in Mac OS X
 * versions 10.4 and higher.  The search query is specified using the syntax of the
 * mdfind command line tool.  This is a powerful syntax which supports wildcards,
 * boolean expressions, and specifications of particular metadata attributes to search.
 * For details, see the documentation for mdfind.
 *
 * @author Peter Eastman
 */


public class Spotlight
{
  /**
   * Perform a Spotlight search.
   *
   * @param query      the query string to search for
   * @return a list of all files and folders matching the search
   */


  public static List<File> find(String query) throws IOException
  {
    return doSearch(new String[] {"mdfind", query});
  }


  /**
   * Perform a Spotlight search.
   *
   * @param query      the query string to search for
   * @param folder     the search will be restricted to files inside this folder
   * @return a list of all files and folders matching the search
   */


  public static List<File> find(String query, File folder) throws IOException
  {
    return doSearch(new String[] {"mdfind", "-onlyin", folder.getAbsolutePath(), query});
  }


  private static List<File> doSearch(String command[]) throws IOException
  {
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()));
    ArrayList<File> results = new ArrayList<File>();
    String line;
    while ((line = out.readLine()) != null)
      results.add(new File(line));
    return results;
  }


  /**
   * Get a map containing all searchable metadata attributes for a particular
   * file or folder.
   *
   * @param file     the file to report on
   * @return a Map containing all metadata for the file
   */


  public static Map<String,String> getMetadata(File file) throws IOException
  {
    Process process = Runtime.getRuntime().exec(new String[] {"mdls", file.getAbsolutePath()});
    BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()));
    HashMap<String,String> results = new HashMap<String,String>();
    String line;
    while ((line = out.readLine()) != null)
    {
      int equals = line.indexOf('=');
      if (equals > -1)
      {
        String key = line.substring(0, equals).trim();
        String value = line.substring(equals+1).trim();
        results.put(key, value);
      }
    }
    return results;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM