Dee*_*pak 9 java resources jar properties
我有一个属性文件,它在一个默认包中,我使用属性文件的类也在同一个默认包中.如果我只使用文件名而没有任何路径我会收到错误.显然这是不正确的,因为我应该给某种路径来引用tat文件.我将构建应用程序使其成为一个jar文件,所以我应该如何给出路径,因为属性文件应该进入该jar文件.我正在使用Netbeans IDE.
编辑
Properties pro = new Properties();
try {
pro.load(new FileInputStream("pos_config.properties"));
pro.setProperty("pos_id", "2");
pro.setProperty("shop_type", "2");
pro.store(new FileOutputStream("pos_config.properties"), null);
String pos_id = pro.getProperty("pos_id");
if(pos_id.equals("")){
pos_id="0" ;
}
global_variables.station_id = Integer.parseInt(pos_id);
String shop_type = pro.getProperty("shop_type");
if(shop_type.equals("")){
shop_type="0" ;
}
global_variables.shop_type = Integer.parseInt(shop_type);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Run Code Online (Sandbox Code Playgroud)
使用 getClass().getResourceAsStream("foo.properties")
但请注意,不建议使用默认包(上述内容适用于任何包).
您的代码不起作用,因为FileInputStream(..)使用相对于当前用户目录的路径(请参阅java.io.File文档).所以它看起来foo.properties在/home/usr/或c:\documents and settings\usr.由于您的.properties文件位于类路径上,因此可以通过该Class.getResourceAsStream(..)方法读取它.
正如其他人所指出的那样,如果您希望能够从jar加载它,则应该从类路径而不是文件中加载它.您需要Class.getResourceAsStream()方法或ClassLoader.getResourceAsStream()方法.但是,使用getClass().getResourceAsStream("pos_config.properties")是危险的,因为您使用的是相对于给定类已解析的路径,并且子类可以更改其解析的位置.因此,在jar中命名绝对路径是最安全的:
getClass().getResourceAsStream("/pos_config.properties")
Run Code Online (Sandbox Code Playgroud)
甚至更好,使用类文字而不是getClass():
Foo.class.getResourceAsStream("pos_config.properties")
Run Code Online (Sandbox Code Playgroud)
您是否尝试从当前工作目录中获取属性文件,或者您是否尝试将其作为资源获取?听起来你应该使用它.
InputStream is = getClass().getResourceAsStream(filename);
properties.load(is);
Run Code Online (Sandbox Code Playgroud)
从当前目录加载文件
properties.load(new FileInputStream(filename));
Run Code Online (Sandbox Code Playgroud)
我的猜测是你真正想要的是这个.
try {
Properties pro = new Properties();
pro.load(new FileInputStream("pos_config.properties"));
String pos_id = pro.getProperty("pos_id");
try {
global_variables.station_id = Integer.parseInt(pos_id);
} catch(Exception e) {
global_variables.station_id = 0;
}
String shop_type = pro.getProperty("shop_type");
try {
global_variables.shop_type = Integer.parseInt(shop_type);
} catch(Exception e) {
global_variables.shop_type = 0;
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77675 次 |
| 最近记录: |