2009-08-19 27 views
5

実行時にファイルからプロパティのセットを読み込む実行可能なJARを作成しています。ディレクトリ構造は次のようになります:JARディレクトリからプロパティファイルを読み取る

/some/dirs/executable.jar 
/some/dirs/executable.properties 

jarファイルが入っているディレクトリからプロパティをロードするためにexecutable.jarファイルのプロパティローダークラスを設定する方法ではなく、ハードコーディングありますディレクトリ。

プロパティファイルを構成可能にする必要があるため、jarファイル自体にプロパティを入れたくありません。

+0

http://stackoverflow.com/questions/775389/accessing-properties-files-outside-the-jarの可能重複 –

答えて

12

プロパティファイルをメインメソッドの引数として渡すだけではどうですか?次のようにそのように、あなたはプロパティをロードすることができます。

public static void main(String[] args) throws IOException { 
    Properties props = new Properties(); 
    props.load(new BufferedReader(new FileReader(args[0]))); 
    System.setProperties(props); 
} 

代替:あなたのjarファイルの現在のディレクトリを取得したい場合はあなたのような厄介な何かをする必要があります。

CodeSource codeSource = MyClass.class.getProtectionDomain().getCodeSource(); 
File jarFile = new File(codeSource.getLocation().toURI().getPath()); 
File jarDir = jarFile.getParentFile(); 

if (jarDir != null && jarDir.isDirectory()) { 
    File propFile = new File(jarDir, "myFile.properties"); 
} 

を...ここでMyClassはjarファイル内のクラスです。私がお勧めしたいものではありません - あなたのアプリケーションが複数の異なるjarファイル(別のディレクトリにある各jar)のクラスパスに複数のMyClassインスタンスを持っていたらどうなりますか?つまり、実際にはMyClassが、それがそうだと思われるジャーからロードされたことを保証することはできません。

0

public static void loadJarCongFile(Class Utilclass) 
 
    { 
 
     try{   
 
      String path= Utilclass.getResource("").getPath(); 
 
      path=path.substring(6,path.length()-1); 
 
      path=path.split("!")[0]; 
 
      System.out.println(path); 
 
      JarFile jarFile = new JarFile(path); 
 

 
       final Enumeration<JarEntry> entries = jarFile.entries(); 
 
       while (entries.hasMoreElements()) { 
 
        final JarEntry entry = entries.nextElement(); 
 
        if (entry.getName().contains(".properties")) { 
 
         System.out.println("Jar File Property File: " + entry.getName()); 
 
         JarEntry fileEntry = jarFile.getJarEntry(entry.getName()); 
 
         InputStream input = jarFile.getInputStream(fileEntry); 
 
         setSystemvariable(input);  
 
         InputStreamReader isr = new InputStreamReader(input); 
 
         BufferedReader reader = new BufferedReader(isr); 
 
         String line; 
 
        
 
         while ((line = reader.readLine()) != null) { 
 
          System.out.println("Jar file"+line); 
 
         } 
 
         reader.close(); 
 
        } 
 
       } 
 
     } 
 
     catch (Exception e) 
 
     { 
 
      System.out.println("Jar file reading Error"); 
 
     } 
 
    } 
 
    public static void setSystemvariable(InputStream input) 
 
    { 
 
    Properties tmp1 = new Properties(); 
 
     try { 
 
      tmp1.load(input); 
 

 
     for (Object element : tmp1.keySet()) { 
 
      System.setProperty(element.toString().trim(), 
 
          tmp1.getProperty(element.toString().trim()).trim()); 
 
      }  
 
     } catch (IOException e) { 
 
      System.out.println("setSystemvariable method failure"); 
 
     } 
 
    }

関連する問題