在Java中调用property文件有多种方法,其中常用的方法有以下几种:
使用java.util.Properties
类:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertyFileExample {
public static void main(String[] args) {
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("path/to/your/property/file.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String value = properties.getProperty("key");
System.out.println("Value: " + value);
}
}
使用java.util.ResourceBundle
类:
import java.util.ResourceBundle;
public class PropertyFileExample {
public static void main(String[] args) {
ResourceBundle resourceBundle = ResourceBundle.getBundle("your.property.file");
String value = resourceBundle.getString("key");
System.out.println("Value: " + value);
}
}
使用java.nio.file.Files
类:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class PropertyFileExample {
public static void main(String[] args) {
Path filePath = Paths.get("path/to/your/property/file.properties");
try {
List<String> lines = Files.readAllLines(filePath);
for (String line : lines) {
if (line.startsWith("key=")) {
String value = line.substring(4);
System.out.println("Value: " + value);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
请根据自己的需求选择适合的方法来调用property文件。