java怎么获取配置文件参数

41次阅读
没有评论

共计 1066 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,可以使用 java.util.Properties 类来读取配置文件中的参数。以下是一个简单的示例:
首先,创建一个名为 config.properties 的配置文件,并在文件中添加以下内容:

name=John Doe
age=30

然后,在 Java 代码中使用 Properties 类读取配置文件中的参数:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {public static void main(String[] args) {Properties properties = new Properties();
FileInputStream configFile = null;
try {configFile = new FileInputStream("config.properties");
properties.load(configFile);
} catch (IOException e) {e.printStackTrace();
} finally {if (configFile != null) {
try {configFile.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
String name = properties.getProperty("name");
int age = Integer.parseInt(properties.getProperty("age"));
System.out.println("Name:" + name);
System.out.println("Age:" + age);
}
}

运行上述代码,将输出以下结果:

Name: John Doe
Age: 30

上述代码中,首先创建了一个 Properties 对象 properties,然后使用FileInputStream 来读取配置文件 config.properties。接着,使用properties.load(configFile) 方法加载配置文件中的参数。最后,使用 getProperty 方法根据参数名获取相应的值。使用 Integer.parseInt 将字符串类型的年龄转换为整数类型。
注意:在使用 FileInputStream 读取配置文件时,需要提供配置文件的路径。上述示例假设配置文件与 Java 代码位于同一目录下,如果不是,请提供正确的路径。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计1066字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)