Person.properties file: name=Alex SunTest file: public static void main(String[] args) { Person p = new Person(); System.out.println(p.name); } three files exist under the same folder, 没有问题。
class 和 properties 文件打包成jar,在外面import就不行了。
AnyClass.class.getClassLoader可以得到给类的路径,就算类被打包在jar里面,java也可以找到jar里面去,没有问题。但是,问题是,从包里面怎样找到包外面的文件呢?用Thread.currentThread().getContentClassLoader()可以解决一些,如果再开一个project,import原先的,用Jbuilder run,Thread.currentThread().getContentClassLoader()可以找到jar外面运行的新的project的class目录。 现在的问题是,当我用bat文件启动程序,bat在bin目录下,jar在lib目录下,classpath is set properly, and the program can start and run properly, but it's not able to locate resource files existed outside the jar. 如果,文件在jar里面,没有问题,有的时候,许多配置文件是不应该在jar里面的,所以就搞不定了。如果用new File好像是bat文件的目录,但是用RresourceBundle和用bat文件启动,怎么也么办法找到与bat文件并列的properties文件。 求解,谢谢。
It's obviously to pack the project in a jar file when delivering to the client. It is also obviously to keep some resource file(s) out from the jar file since some properties need to be setup manuelly by the client, or some resource files are dynamic, such as the high score file.
Using batch file to start the project, bat file is under bin directory, jar file is under lib directory along with other required libraries. as someone just suggested, leave the resource file under the jar folder. How exactly to get the ini file? As I said, I had tried ResourceBundle.getResource("..", default local, Thread.currentThread().getContentClassLoader()), but it won't work; throwing me a Unfound Resource Exception.
import java.util.*;
public class Person
{
String name;
public Person()
{
try
{
ResourceBundle rb = ResourceBundle.getBundle("Person");
name = rb.getString("name");
}
catch (Exception ex)
{
name = "Unknown Name";
}
}
}
这样可以找到你的实际路径:URL url=ClassLoader.getSystemResource("当前类");
String path=url.getPath();
name=Alex SunTest file:
public static void main(String[] args)
{
Person p = new Person();
System.out.println(p.name);
}
three files exist under the same folder, 没有问题。
现在的问题是,当我用bat文件启动程序,bat在bin目录下,jar在lib目录下,classpath is set properly, and the program can start and run properly, but it's not able to locate resource files existed outside the jar. 如果,文件在jar里面,没有问题,有的时候,许多配置文件是不应该在jar里面的,所以就搞不定了。如果用new File好像是bat文件的目录,但是用RresourceBundle和用bat文件启动,怎么也么办法找到与bat文件并列的properties文件。
求解,谢谢。
比如叫做classa.properties,就在文件里面写
Properties prop = new Properties();
prop.load(fileinput)
我昨天也查了一下这个ResourceBundle.getResource,是在类路径下找文件的。应该是这个意思吧