Java 如何从属性文件中读取值?

Java 如何从属性文件中读取值?,java,properties-file,Java,Properties File,如何在java脚本中从属性文件中读取值 我目瞪口呆,但不满意。请与我分享一些样品或链接。我的应用程序由jsp servlet、eclipse LUNA和Windows7开发。您可以通过多种方式读取属性文件,下面是其中一种方式 配置属性 dbpassword=password database=localhost dbuser=mkyong App.java package com.mkyong.properties; import java.io.FileInputStream; import

如何在java脚本中从属性文件中读取值


我目瞪口呆,但不满意。请与我分享一些样品或链接。我的应用程序由jsp servlet、eclipse LUNA和Windows7开发。

您可以通过多种方式读取属性文件,下面是其中一种方式

配置属性

dbpassword=password
database=localhost
dbuser=mkyong
App.java

package com.mkyong.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App {
  public static void main(String[] args) {

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("config.properties");

    // load a properties file
    prop.load(input);

    // get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}
}

Javascript在客户端执行,无法访问本地文件(html5 web存储除外)

如果要访问在服务器端的属性文件中定义的属性,有两个选项:

服务器端解析

读取服务器端的属性文件,并将值作为JS值写入html响应

// output a property as JS value to the client. Make sure this is inside a 
// <script> tag
void printProperty(Properties properties, String key) {
   Sytem.out.println("var " + key + "='"properties.getProperty("key") + "'");
}
//将属性作为JS值输出到客户端。确保这是在一个盒子里
//标签
void printProperty(属性,字符串键){
system.out.println(“var”+key+“='”properties.getProperty(“key”)+“””);
}
客户端解析(更复杂)

  • 通过URL(http:/…/conf.properties)使属性文件可用
  • 通过ajax读取文件
  • 解析属性文件

  • 你不能用javascript阅读。它必须用Java读取。那么用Java读取并使用jsp/Java脚本中的值的有效方法是什么呢?您可以使用我在ans中提到的方法