栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在JAR文件之外读取属性文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在JAR文件之外读取属性文件

因此,你希望将

.properties
与主/可运行jar相同文件夹中的文件视为文件,而不是作为主/可运行jar的资源。在这种情况下,我自己的解决方案如下:

首先,第一件事:你的程序文件架构应如下所示(假设你的主程序是main.jar,其主要属性文件是main.properties):

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

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

app.version=1.0.0.0app.name=Hello

因此,当你从主程序的根目录/基本目录运行主程序时,通常会这样运行它:

java -jar ./main.jar

或者,立即:

java -jar main.jar

main.jar
中,你需要为
main.properties
文件中找到的每个属性创建一些实用程序方法。假设该
app.version
属性具有以下
getAppVersion()
方法:

import java.util.Properties;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();}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420348.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号