Java 中什么是配置文件
Java中的配置文件名称一般都以“.properties”和“.xml”进行结尾,这些配置文件的结构都和Java的HashMap结构是一样的,其作用是通过修改配置文件来实现代码中的参数的更改,从而实现灵活变更参数。
properties使用
driver=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/user user=root password=123456
/** * 读取config.properties文件中的内容,放到Properties类中 * @param filePath 文件路径 * @param key 配置文件中的key * @return 返回key对应的value */ public static String readConfigFiles(String filePath,String key) { Properties prop = new Properties(); try{ InputStream inputStream = new FileInputStream(filePath); prop.load(inputStream); inputStream.close(); return prop.getProperty(key); }catch (Exception e) { e.printStackTrace(); System.out.println("未找到相关配置文件"); return null; } }
xml使用
<?xml version="1.0" encoding="utf-8" ?> <class> <student> <firstname>cxx1</firstname> <lastname>Bob1</lastname> <nickname>stars1</nickname> <marks>85</marks> </student> <student rollno="493"> <firstname>cxx2</firstname> <lastname>Bob2</lastname> <nickname>stars2</nickname> <marks>85</marks> </student> <student rollno="593"> <firstname>cxx3</firstname> <lastname>Bob3</lastname> <nickname>stars3</nickname> <marks>85</marks> </student> </class>
package com.cxx.xml; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * @Author: cxx * Dom操作xml * @Date: 2018/5/29 20:19 */ public class DomDemo { //用Element方式 public static void element(NodeList list){ for (int i = 0; i <list.getLength() ; i++) { Element element = (Element) list.item(i); NodeList childNodes = element.getChildNodes(); for (int j = 0; j <childNodes.getLength() ; j++) { if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) { //获取节点 System.out.print(childNodes.item(j).getNodeName() + ":"); //获取节点值 System.out.println(childNodes.item(j).getFirstChild().getNodeValue()); } } } } public static void node(NodeList list){ for (int i = 0; i <list.getLength() ; i++) { Node node = list.item(i); NodeList childNodes = node.getChildNodes(); for (int j = 0; j <childNodes.getLength() ; j++) { if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) { System.out.print(childNodes.item(j).getNodeName() + ":"); System.out.println(childNodes.item(j).getFirstChild().getNodeValue()); } } } } public static void main(String[] args) { //1.创建DocumentBuilderFactory对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //2.创建DocumentBuilder对象 try { DocumentBuilder builder = factory.newDocumentBuilder(); Document d = builder.parse("src/main/resources/demo.xml"); NodeList sList = d.getElementsByTagName("student"); //element(sList); node(sList); } catch (Exception e) { e.printStackTrace(); } } }
推荐教程:《Java教程》
Atas ialah kandungan terperinci Java 中什么是配置文件. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!