從Eclipse plugin中讀文件

進行Eclipse插件開發或者RCP開發的時候,常常遇到這樣的需求:程序員準備了幾個文件打在jar包裏,在程序運行的時候由用戶的操作觸發,要讀jar包裏的這幾個文件,顯示內容在界面上,或者直接複製文件到用戶的目錄中。這裏提供兩種直截了當的方法來實現這一目的。

第一,使用OSGi自帶的utility class / methods,例子中的com.company.example是bundle (或者plugin) 的id,要讀的文件是這個bundle中 resources文件夾中的 backup.txt 文件。

Bundle bundle = Platform.getBundle("com.company.example");
URL fileURL = bundle.getEntry("resources/backup.txt");
File file = null;
try {
    file = new File(FileLocator.resolve(fileURL).toURI());
} catch (URISyntaxException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

第二,不依賴OSGi Platform,直接使用platform協議(platform:/plugin)生成URL,例子中的com.company.example是bundle (或者plugin) 的id,要讀的文件是這個bundle中 resources文件夾中的 backup.txt 文件。

URL url;
try {
    url = new URL("platform:/plugin/com.company.example/resources/backup.txt");
    InputStream inputStream = url.openConnection().getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }
    in.close();
} catch (IOException e) {
    e.printStackTrace();
}


如果要拷貝文件到Eclipse RCP項目 (生成IFile) 的話,直接用org.eclipse.core.resources.IFile的

void create(InputStream source,
            int updateFlags,
            IProgressMonitor monitor)
            throws CoreException

方法以及利用URL.openConnection()得到的 InputStream來生成。


第二種方法比第一種有幾個優點:

1、不需要import org.eclipse.core.runtime,org.osgi.framework包,

或者depend on org.eclipse.core.runtime這個bundle

2、org.osgi.framework.Bundle的 getEntry(String path) 方法對於不同的文件系統協議有不同的處理方式,比如file:/, jar:/, zip:/ 都有細微差別

從下面粘貼的官方文檔中模棱兩可的解釋就可見一斑,一不小心就可能出錯,而且在不同環境中可能會出現意想不到的bug (比如在Eclipse環境下工作的好好的,各個bundle都打成jar包以後可能就會路徑報錯)


getEntry

java.net.URL getEntry(java.lang.String path)
Returns a URL to the entry at the specified path in this bundle. This bundle's class loader is not used to search for the entry. Only the contents of this bundle are searched for the entry.

The specified path is always relative to the root of this bundle and may begin with "/". A path value of "/" indicates the root of this bundle.

Note: Jar and zip files are not required to include directory entries. URLs to directory entries will not be returned if the bundle contents do not contain directory entries.

Parameters:
path - The path name of the entry.
Returns:
A URL to the entry, or null if no entry could be found or if the caller does not have the appropriateAdminPermission[this,RESOURCE] and the Java Runtime Environment supports permissions.
Throws:
java.lang.IllegalStateException - If this bundle has been uninstalled.
Since:
1.3



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章