读取JAR文件外的属性文件

我有一个JAR文件,我所有的代码被存档运行。 我必须在每次运行之前访问需要更改/编辑的属性文件。 我想保留属性文件在JAR文件所在的同一个目录中。 有无论如何告诉Java拿起该目录的属性文件?

注意:我不想将属性文件保存在主目录中,或者在命令行参数中传递属性文件的path。

所以,你想把你的.properties文件作为一个文件与主/可运行jar放在同一个文件夹中,而不是作为main / runnable jar的资源。 在这种情况下,我自己的解决scheme如下:

首先,你的程序文件结构应该是这样的(假设你的主程序是main.jar,其主属性文件是main.properties):

 ./ - the root of your program |__ main.jar |__ main.properties 

使用这种体系结构,您可以在main.jar运行之前或之中使用任何文本编辑器修改main.properties文件中的任何属性(取决于程序的当前状态),因为它只是一个基于文本的文件。 例如,你的main.properties文件可能包含:

 app.version=1.0.0.0 app.name=Hello 

所以,当你从它的root / base文件夹运行你的主程序时,通常你会像这样运行它:

 java -jar ./main.jar 

或者,马上:

 java -jar main.jar 

在main.jar中,需要为main.properties文件中的每个属性创build一些实用程序方法; 假设app.version属性将具有getAppVersion()方法,如下所示:

 /** * Gets the app.version property value from * the ./main.properties file of the base folder * * @return app.version string * @throws IOException */ public static String getAppVersion() throws IOException{ String versionString = null; //to load application's properties, we use this class Properties mainProperties = new Properties(); FileInputStream file; //the base folder is ./, the root of the main.properties file String path = "./main.properties"; //load the file handle for main.properties file = new FileInputStream(path); //load all the properties from this file mainProperties.load(file); //we have loaded the properties, so close the file handle file.close(); //retrieve the property we are intrested, the app.version versionString = mainProperties.getProperty("app.version"); return versionString; } 

在需要app.version值的主程序的任何部分,我们调用它的方法如下:

 String version = null; try{ version = getAppVersion(); } catch (IOException ioe){ ioe.printStackTrace(); } 

我以其他方式做了。

 Properties prop = new Properties(); try { File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()); String propertiesPath=jarPath.getParentFile().getAbsolutePath(); System.out.println(" propertiesPath-"+propertiesPath); prop.load(new FileInputStream(propertiesPath+"/importer.properties")); } catch (IOException e1) { e1.printStackTrace(); } 
  1. 获取Jar文件path。
  2. 获取该文件的父文件夹。
  3. 在InputStreamPath中用你的属性文件名来使用这个path。

从jar文件访问文件目录中的文件总是有问题。 在jar文件中提供类path非常有限。 请尝试使用bat文件或sh文件来启动程序。 通过这种方式,您可以随意指定您的类path,并引用系统上任何位置的任何文件夹。

还请检查我对这个问题的答案:

为包含sqlite的java项目制作.exe文件

我有一个类似的情况:想让我的*.jar文件访问*.jar文件旁边目录中的文件。 请参阅本答复 。

我的文件结构是:

 ./ - the root of your program |__ *.jar |__ dir-next-to-jar/some.txt 

我能够加载一个文件(比如some.txt )到*.jar文件中的InputStream中,内容如下:

 InputStream stream = null; try{ stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt"); } catch(Exception e) { System.out.print("error file to stream: "); System.out.println(e.getMessage()); } 

然后做任何你想要的stream