在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文件。