1. 程式人生 > >利用反射動態獲取當前工程下的檔案路徑_並打成jar包

利用反射動態獲取當前工程下的檔案路徑_並打成jar包

這一次我把它打包成jar包,方便隨時匯入使用。

新程式碼工程目錄:

檔案路徑類FilePath.java:

package filepath;

import java.io.File;

public class FilePath  
{  
    //當前的工程下的路徑  
    public static String getProjectPath()  
    {  
          
        return System.getProperty("user.dir").toString()+"\\";  
  
    }  
    
  //編譯之後src下的檔案路徑,根據工程路徑拼接  
    public static String getSrcPath()  
    {  
        return System.getProperty("user.dir").toString()+"\\bin\\";  
    }  
    //根據反射獲取編譯之後的src下面的檔案路徑  
    public static String getSrcPath(Class<?> class1)  
    {  
        String path = class1.getClassLoader().getResource("").toString();  
        // System.out.println("編譯後src路徑:"+path);//file:/D:/dev/workspase2Spring/XMLreader/bin/  
        int m = path.indexOf("/");// file:/<----點位到file:後面的反斜槓  
        path = path.substring(m + 1);// 從反斜槓之後的一位開始擷取字串  
        // System.out.println("編譯後src路徑:"+path);  
        return path;  
    }  
  //根據反射獲取編譯之後包下面的檔案路徑  
    public static String getPackagePath(Class<?> class1)  
    {  
	//獲取包路徑
        String thisPackagePath=class1.getResource("").toString();  
//        System.out.println("路徑:"+thisPackagePath);  
        int m=thisPackagePath.indexOf("/");//去掉前面的file:  
        thisPackagePath=thisPackagePath.substring(m+1);  
//        System.out.println("路徑:"+thisPackagePath);  
        return thisPackagePath;//返回當前包返回的路徑。  
    }
    public static String getProjectPath(Class<?> class1)  
    {  
	//獲取src路徑
        String path = class1.getClassLoader().getResource("").toString();  
        // System.out.println("編譯後src路徑:"+path);//file:/D:/dev/workspase2Spring/XMLreader/bin/  
        //檔案定位到src路徑
        File file=new File(path);//定位到這個目錄下面
        path=file.getParent();//返回src路徑的父路徑,也就是工程路徑
//      結果 path=file:\D:\dev\workspase4javaBasis\FilePath
        int m = path.indexOf("\\");// file:\<----點位到file:後面的反斜槓  
        path = path.substring(m + 1);// 從反斜槓之後的一位開始擷取字串  
        // System.out.println("編譯後src路徑:"+path);  
        return path;  
    }  
  //  public static void main(String[] args)
  //  {
	//System.out.println(FilePath.getProjectPath(FilePath.class));
  //  }
}  

下面介紹怎麼把這個工具類打成jar包,以便後面我們重複使用。

步驟如圖:

這樣就匯出到你讀路徑下了,我這裡是D:\dev\myJAR

進入你儲存的目錄,這是已經生成一個名為FilePath.jar的jar包了

然後接著在其他工程裡匯入這個jar包,就可以使用包下面的各種方法啦

匯入的步驟:

然後到剛才儲存的路徑下選擇你的jar包

新建一個測試類Test.java

Test.java程式碼:

package com.lan.testMyJar;

import filepath.FilePath;

public class Test
{
    public static void main(String[] args)
    {
	System.out.println("當前的包路徑為:"+FilePath.getPackagePath(Test.class));
	System.out.println("當前的工程路徑為:"+FilePath.getProjectPath());
	System.out.println("當前的工程路徑為:"+FilePath.getPackagePath(Test.class));
	System.out.println("編譯後的src路徑為:"+FilePath.getSrcPath());
	System.out.println("編譯後的src路徑為:"+FilePath.getSrcPath(Test.class));
	
    }
}
說明:


執行測試類,結果:

可以看到這幾個方法分別獲到了編譯之後的包路徑,src路徑(也就是bin),以及工程路徑(工程路徑不變)

下載我的FilePath.jar:剛上傳後面再補上鍊接