Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

用Java在Windows上模擬Unix/Linux檔案路徑

大部分Java應用跑在UNIX/Linux上,而絕大部分開發在Windows下完成。Java號稱可以運行在anywhere,但環境配置的問題從來不少。

例如在UNIX下,你往往需要把某些配置檔的路徑寫進另一個配置檔,受限於環境,很多時候必須填絕對路徑:

logs = /logs/app/db/logs.properties
configs=/usr/WebSphere/AppServer/installedApps/appname/earname/warname/WEB-INF/properties/myconfig.properties

開發階段,你願意在Windows開發機上一個個建出這些目錄,或逐一改寫路徑嗎?尤其是在既有系統上為了新功能重建開發環境時,改配置路徑極度耗時。釋版時你還得用Ant批量替換,但多數項目只有生產與系統整合測試環境才配了Ant,低階測試環境只能手動改。那麼,如何不改任何檔案就在Windows本機除錯並運行?下面給一個小方案。

1. 改寫java.io.File類

先別丟香蕉皮,改寫java.io.File並不需要動rt.jar。JVM支援pretend(偽裝),可以在運行期用自訂的java.io.File取代rt.jar裡的原版。細節可參考[JAVA_HOME]\bin\client\Xusage.txt:

-Xbootclasspath/p:<directories and zip/jar files separated by ;>
                    prepend in front of bootstrap class path

把改寫後的類打包成filemap_1_4.jar,除錯時這樣啟動:

java -Xbootclasspath/p:D:\MyProject\FileMap/filemap_1_4.jar -cp ...

如此一來,所有涉及檔案與檔案系統的呼叫,都會走這個jar裡的java.io.File,而不是rt.jar。

2. 功能實作

2.1 目錄映射關係。為了增加靈活性,用一個映射檔定義UNIX/Linux路徑與Windows路徑的對應,例如filemap.properties:

/usr/WebSphere/AppServer/installedApps/appname/earname/warname/=C:/MyProject/
/logs/app/db/=c:/MyProject/logs

當程式要讀/usr/WebSphere/AppServer/installedApps/appname/earname/warname/WEB-INF/properties/myconfig.properties時,java.io.File會把它映射到C:/MyProject/WEB-INF/properties/myconfig.properties。

2.2 在java.io.File中新增一個靜態變數保存映射關係,並用私有方法初始化:

private static HashMap filemaps = null;

/* 讀取filemap.properties以初始化映射表 */
private void initmaps(){
    if(filemaps == null){
        filemaps = new HashMap();
        String filemap = System.getProperty("filemap");
        // 需於JVM啟動時傳入 -Dfilemap=[filemap.properties全路徑]
        // 不要改用 classloader.getResource(),因為它內部也會用到java.io.File,會造成JVM異常
        if(filemap == null || filemap == "") return;
        this.path = fs.normalize(filemap);   // 暫時指向filemap.properties
        this.prefixLength = fs.prefixLength(this.path);
        Properties pro = new Properties();
        try {
            pro.load(new FileInputStream(this));
            Enumeration enumeration = pro.propertyNames();
            while(enumeration.hasMoreElements()){
                String sourcepath = (String)enumeration.nextElement();
                String targetpath = pro.getProperty(sourcepath);
                filemaps.put(sourcepath, targetpath);
            }
        } catch (FileNotFoundException e1){ return; }
          catch (IOException e2){ return; }
    }
}

/* 取得虛擬路徑 */
private String getVirtualPath(String name){
    Iterator sources = filemaps.keySet().iterator();
    while(sources.hasNext()){
        String source = (String)sources.next();
        if(name.startsWith(source) == true){
            String target = (String)filemaps.get(source);
            name = target + name.substring(source.length());
        }
    }
    return name;
}

接著在java.io.File的三個建構子中呼叫這兩個方法:

public File(String pathname) {
    initmaps();
    if (pathname == null) { throw new NullPointerException(); }
    pathname = getVirtualPath(pathname);
    this.path = fs.normalize(pathname);
    this.prefixLength = fs.prefixLength(this.path);
}

public File(String parent, String child) {
    initmaps();
    if (child == null) { throw new NullPointerException(); }
    child = getVirtualPath(child);
    parent = getVirtualPath(parent);
    if (parent != null) {
        if (parent.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(), fs.normalize(child));
        } else {
            this.path = fs.resolve(fs.normalize(parent), fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}

public File(File parent, String child) {
    initmaps();
    child = getVirtualPath(child);
    if (child == null) { throw new NullPointerException(); }
    if (parent != null) {
        if (parent.path.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(), fs.normalize(child));
        } else {
            this.path = fs.resolve(parent.path, fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}

2.3 把java.io.File編譯打包成filemap_1_4.jar。

2.4 設定除錯環境:這個jar不需要放進classpath,但要在VM arguments加上:

-Xbootclasspath/p:C:\MyProject\filemap_1_4.jar -Dfilemap=C:\MyProject\filemap.properties

3. 測試

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) {
        try {
            // 印出 /usr/WebSphere/AppServer/InstallApp/Test.java
            FileReader filereader = new FileReader(
                "/usr/WebSphere/AppServer/InstallApp/Test.java");
            BufferedReader bufferedreader = new BufferedReader(filereader);
            String line = null;
            while((line = bufferedreader.readLine()) != null)
                System.out.println(line);

            // 遍歷該檔案所在目錄並印出檔名
            File fl = new File("/usr/WebSphere/AppServer/InstallApp/Test.java");
            String path = fl.getParent();
            String[] files = new File(path).list();
            for(int i = 0; i < files.length; i++){
                System.out.println(files[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copyright © Linux教程網 All Rights Reserved