Java 本身没有直接支持常量的功能,但你可以使用以下方法在 Java 配置文件中存储和使用常量:
创建一个名为 config.properties
的文件,并在其中定义常量。例如:
app.name=My Application
app.version=1.0.0
然后,在 Java 代码中读取这些常量:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties properties = new Properties();
InputStream inputStream = ConfigReader.class.getClassLoader().getResourceAsStream("config.properties");
try {
properties.load(inputStream);
String appName = properties.getProperty("app.name");
String appVersion = properties.getProperty("app.version");
System.out.println("App Name: " + appName);
System.out.println("App Version: " + appVersion);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
创建一个名为 config.xml
的文件,并在其中定义常量。例如:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<application>
<name>My Application</name>
<version>1.0.0</version>
</application>
</config>
然后,在 Java 代码中读取这些常量:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ConfigReader {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(ConfigReader.class.getClassLoader().getResourceAsStream("config.xml"));
Element rootElement = document.getDocumentElement();
NodeList nameList = rootElement.getElementsByTagName("name");
NodeList versionList = rootElement.getElementsByTagName("version");
String appName = nameList.item(0).getTextContent();
String appVersion = versionList.item(0).getTextContent();
System.out.println("App Name: " + appName);
System.out.println("App Version: " + appVersion);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
这两种方法都可以用于在 Java 配置文件中存储和使用常量。