如何使用 Java 属性文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1318347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:10:56  来源:igfitidea点击:

How to use Java property files?

javaproperties

提问by Click Upvote

I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.

我有一个配置值的键/值对列表,我想存储为 Java 属性文件,稍后加载和迭代。

Questions:

问题:

  • Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?
  • Does the file need to end in any specific extension or is .txtOK?
  • How can I load the file in the code
  • And how can I iterate through the values inside?
  • 我是否需要将文件与加载它们的类存储在同一个包中,或者是否有任何特定的位置应该放置它?
  • 文件需要以任何特定的扩展名结尾还是.txt可以?
  • 如何在代码中加载文件
  • 以及如何遍历内部的值?

采纳答案by Zed

You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.

您可以将 InputStream 传递给属性,因此您的文件几乎可以在任何地方,并且可以调用任何内容。

Properties properties = new Properties();
try {
  properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
  ...
}

Iterate as:

迭代为:

for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}

回答by Alberto Zaccagni

This load the properties file:

这将加载属性文件:

Properties prop = new Properties();
InputStream stream = ...; //the stream to the file
try {
  prop.load(stream);
} finally {
  stream.close();
}

I use to put the .properties file in a directory where I have all the configuration files, I do not put it together with the class that accesses it, but there are no restrictions here.

我习惯将 .properties 文件放在我拥有所有配置文件的目录中,我没有将它与访问它的类放在一起,但这里没有任何限制。

For the name... I use .properties for verbosity sake, I don't think you should name it .properties if you don't want.

对于名称...我使用 .properties 是为了详细起见,如果您不想要,我认为您不应该将其命名为 .properties。

回答by Thierry-Dimitri Roy

By default, Java opens it in the working directory of your application (this behavior actually depends on the OS used). To load a file, do:

默认情况下,Java 在应用程序的工作目录中打开它(此行为实际上取决于所使用的操作系统)。要加载文件,请执行以下操作:

Properties props = new java.util.Properties();
FileInputStream fis new FileInputStream("myfile.txt");
props.load(fis)

As such, any file extension can be used for property file. Additionally, the file can also be stored anywhere, as long as you can use a FileInputStream.

因此,任何文件扩展名都可以用于属性文件。此外,该文件也可以存储在任何地方,只要您可以使用FileInputStream.

On a related note if you use a modern framework, the framework may provide additionnal ways of opening a property file. For example, Spring provide a ClassPathResourceto load a property file using a package name from inside a JAR file.

在相关说明中,如果您使用现代框架,该框架可能会提供打开属性文件的其他方式。例如,Spring 提供了ClassPathResource使用 JAR 文件中的包名加载属性文件的方法。

As for iterating through the properties, once the properties are loaded they are stored in the java.util.Propertiesobject, which offer the propertyNames()method.

至于遍历属性,一旦加载了属性,它们就会存储在java.util.Properties提供propertyNames()方法的对象中。

回答by Jon Skeet

  • You canstore the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream()or ClassLoader.getResourceAsStream()to access it. If it's on the file system it's slightly easier.

  • Any extension is fine, although .properties is more common in my experience

  • Load the file using Properties.load, passing in an InputStreamor a StreamReaderif you're using Java 6. (If you areusing Java 6, I'd probably use UTF-8 and a Readerinstead of the default ISO-8859-1 encoding for a stream.)

  • Iterate through it as you'd iterate through a normal Hashtable(which Propertiesderives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().

  • 可以将文件存储在您喜欢的任何位置。如果您想将它保存在您的 jar 文件中,您将需要使用Class.getResourceAsStream()ClassLoader.getResourceAsStream()访问它。如果它在文件系统上,它会稍微容易一些。

  • 任何扩展名都可以,尽管 .properties 在我的经验中更常见

  • 使用加载该文件Properties.load,通过在一个InputStream或一个StreamReader,如果你使用的是Java 6(如果您正在使用Java 6,我可能会使用UTF-8和Reader而不是默认的ISO-8859-1编码流。 )

  • 像遍历法线HashtableProperties派生自)一样遍历它,例如使用keySet(). 或者,您可以使用由 返回的枚举propertyNames()

回答by Brian Agnew

In order:

为了:

  1. You can store the file pretty much anywhere.
  2. no extension is necessary.
  3. Montecristo has illustratedhow to load this. That should work fine.
  4. propertyNames()gives you an enumeration to iterate through.
  1. 您几乎可以将文件存储在任何地方。
  2. 不需要扩展。
  3. Montecristo 已经说明了如何加载它。那应该可以正常工作。
  4. propertyNames()为您提供一个枚举以进行迭代。

回答by adatapost

There are many ways to create and read propertiesfiles:

创建和读取properties文件的方法有很多:

  1. Store the file in the same package.
  2. Recommend .propertiesextension however you can choose your own.
  3. Use theses classes located at java.utilpackage => Properties, ListResourceBundle, ResourceBundleclasses.
  4. To read properties, use iterator or enumerator or direct methods of Propertiesor java.lang.Systemclass.
  1. 将文件存储在同一个包中。
  2. 推荐.properties扩展,但您可以选择自己的扩展。
  3. 使用位于java.utilpackage => Properties, ListResourceBundle, ResourceBundleclasses 的这些类。
  4. 要读取属性,请使用迭代器或枚举器Propertiesjava.lang.System类的直接方法。

ResourceBundleclass:

ResourceBundle班级:

 ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
 System.out.println(rb.getString("key"));

Propertiesclass:

Properties班级:

Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));

回答by Fabian Steeg

If you put the properties file in the same package as class Foo, you can easily load it with

如果将属性文件与类 Foo 放在同一个包中,则可以轻松加载它

new Properties().load(Foo.class.getResourceAsStream("file.properties"))

Given that Properties extends Hashtable you can iterate over the values in the same manner as you would in a Hashtable.

鉴于 Properties 扩展了 Hashtable,您可以以与在 Hashtable 中相同的方式迭代这些值。

If you use the *.properties extension you can get editor support, e.g. Eclipse has a properties file editor.

如果您使用 *.properties 扩展名,您可以获得编辑器支持,例如 Eclipse 有一个属性文件编辑器。

回答by dertoni

Here is another way to iterate over the properties:

这是迭代属性的另一种方法:

Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) { 
    String key = (String) eProps.nextElement(); 
    String value = properties.getProperty(key); 
    System.out.println(key + " => " + value); 
}

回答by zubair

Example:

例子:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file 
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ",";                         //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);

回答by FrederikH

I have written on this property framework for the last year. It will provide of multiple ways to load properties, and have them strongly typed as well.

我去年写过这个属性框架。它将提供多种方法来加载属性,并让它们强类型化。

Have a look at http://sourceforge.net/projects/jhpropertiestyp/

看看http://sourceforge.net/projects/jhpropertiestyp/

JHPropertiesTyped will give the developer strongly typed properties. Easy to integrate in existing projects. Handled by a large series for property types. Gives the ability to one-line initialize properties via property IO implementations. Gives the developer the ability to create own property types and property io's. Web demo is also available, screenshots shown above. Also have a standard implementation for a web front end to manage properties, if you choose to use it.

JHPropertiesTyped 将为开发人员提供强类型属性。易于集成到现有项目中。由属性类型的大系列处理。提供通过属性 IO 实现单行初始化属性的能力。使开发人员能够创建自己的属性类型和属性 io。也可以使用 Web 演示,截图如上所示。如果您选择使用它,还可以使用 Web 前端的标准实现来管理属性。

Complete documentation, tutorial, javadoc, faq etc is a available on the project webpage.

项目网页上提供了完整的文档、教程、javadoc、faq 等。