Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JAVA上加载属性文件的最佳方式是什么_Java_File_Properties - Fatal编程技术网

在JAVA上加载属性文件的最佳方式是什么

在JAVA上加载属性文件的最佳方式是什么,java,file,properties,Java,File,Properties,可能重复: 我想知道在JAVA上加载.property文件的最佳方式是什么,我在这里四处寻找,但找不到我要查找的内容。问题是加载它的最佳方式是什么。 我用它来开发游戏 问候,, 米格怎么样 Properties properties = new Properties(); BufferedInputStream stream = new BufferedInputStream(new FileInputStream("example.properties")); properties.load

可能重复:

我想知道在JAVA上加载.property文件的最佳方式是什么,我在这里四处寻找,但找不到我要查找的内容。问题是加载它的最佳方式是什么。 我用它来开发游戏

问候,, 米格

怎么样

Properties properties = new Properties();
BufferedInputStream stream = new BufferedInputStream(new FileInputStream("example.properties"));
properties.load(stream);
stream.close();
String sprache = properties.getProperty("lang");
如果foo.properties的文件路径与加载属性文件的类不在同一个包中,则需要更改它。例如,如果.properties文件位于
com.example.properties.here
中,则将以下文件路径用于
InputStream


InputStream InputStream=getClass().getResourceAsStream(“/com/example/properties/here/foo.properties”)

此解决方案与UTF-8配合使用,并自动发现类路径中的属性

公共类I18nBean{
私有资源包;
私有静态I18nBean实例=新I18nBean(“app”);//app.properties
公共静态I18nBean getInstance(){
返回实例;
}
/**
@param propertyFileName-不带扩展名,即
如果您有app.properties,请传递“app”
*/
私有I18nBean(字符串属性文件名){
resourceBundle=resourceBundle.getBundle(propertyFileName);
}
公共字符串获取(字符串键){
试一试{
String foundString=resourceBundle.getString(键);
返回convertToUTF8(foundString);
}捕获(丢失资源异常e){
返回“”;
}
}
私有字符串转换器TOUTF8(字符串str){
试一试{
返回新字符串(str.getBytes(“ISO-8859-1”)、Charset.forName(“UTF-8”);
}捕获(不支持的编码异常e){
return str;//不是真正的大小写
}
}
}

用法:

I18nBean i18nBean = I18nBean.getInstance();
i18nBean.get("application.name");

Upvote提供了加载属性后如何获取属性的示例。需要注意的是,Properties类默认仅支持ISO 8859-1,如果要支持unicode字符,这可能是一个问题。但您始终可以覆盖默认实现以本机支持unicode字符。@dinukadev:对于Java7,您可以使用
读取器
加载属性。这样也支持UTF-8。可以通过在ISO编码的属性文件中转义unicode字符(例如
\u201d
)来包括unicode字符。NetBeans属性编辑器将自动执行此操作。嘿,谢谢你的提示。其实我不知道。。干杯使用
Properties
类有什么错?我想这会对我有更多帮助,因为我必须为游戏记录ascii数据包。我测试了它,它和另一个一样在同一时间得到了我,但我认为缓冲比普通的InputStream更好。请帮我回答这个问题。在这方面,BufferedReader通常效率更高,因为(顾名思义)缓冲它读取的内容,减少了所需的低级I/O操作。但是,在我提供的示例中,getClass().getResourceAsStream()返回一个InputStream,因此您需要使用它。基于此,我同意PKeidel的答案是更好的,因为它使用了更高效的BufferedReader。谢谢你解决我的问题!
I18nBean i18nBean = I18nBean.getInstance();
i18nBean.get("application.name");