在纯Java中,可以使用`java.util.Properties`类来读取属性文件。下面是一个简单的示例:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
public static void main(String[] args) {
Properties properties = new Properties();
InputStream inputStream = null;
try {
// 读取属性文件
inputStream = new FileInputStream("config.properties");
properties.load(inputStream);
// 获取属性值
String propertyValue = properties.getProperty("property.name");
System.out.println("propertyValue: " + propertyValue);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在上述代码中,`config.properties`是属性文件的名称,`property.name`是需要获取的属性值的键。使用`Properties`类的`load`方法可以将属性文件加载到`Properties`对象中,然后使用`getProperty`方法获取属性值。
需要注意的是,属性文件需要放在正确的位置,以便程序能够找到它。可以使用绝对路径或相对路径来指定属性文件的位置。
另外,还可以使用`ClassLoader`来加载属性文件,例如:
inputStream = ReadProperties.class.getClassLoader().getResourceAsStream("config.properties");
这样可以直接从类路径中加载属性文件。
总之,在纯Java中可以使用`Properties`类来读取属性文件,并通过键来获取属性值。