Java&Xml教程(十)XML作为属性文件使用
我们通常会将Java应用的配置参数保存在属性文件中,Java应用的属性文件可以是一个正常的基于key-value对,以properties为扩展名的文件,也可以是XML文件.
在本案例中,將会向大家介绍如何通过Java程序输出这两种格式的属性文件,并介绍如何从classpath中加载和使用这两种属性文件。
下面是案例程序代码:
PropertyFilesUtil.java
package com.journaldev.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; public class PropertyFilesUtil { public static void main(String[] args) throws IOException { String propertyFileName = "DB.properties"; String xmlFileName = "DB.xml"; writePropertyFile(propertyFileName, xmlFileName); readPropertyFile(propertyFileName, xmlFileName); readAllKeys(propertyFileName, xmlFileName); readPropertyFileFromClasspath(propertyFileName); } /** * read property file from classpath * @param propertyFileName * @throws IOException */ private static void readPropertyFileFromClasspath(String propertyFileName) throws IOException { Properties prop = new Properties(); prop.load(PropertyFilesUtil.class.getClassLoader().getResourceAsStream(propertyFileName)); System.out.println(propertyFileName +" loaded from Classpath::db.host = "+prop.getProperty("db.host")); System.out.println(propertyFileName +" loaded from Classpath::db.user = "+prop.getProperty("db.user")); System.out.println(propertyFileName +" loaded from Classpath::db.pwd = "+prop.getProperty("db.pwd")); System.out.println(propertyFileName +" loaded from Classpath::XYZ = "+prop.getProperty("XYZ")); } /** * read all the keys from the given property files * @param propertyFileName * @param xmlFileName * @throws IOException */ private static void readAllKeys(String propertyFileName, String xmlFileName) throws IOException { System.out.println("Start of readAllKeys"); Properties prop = new Properties(); FileReader reader = new FileReader(propertyFileName); prop.load(reader); Set<Object> keys= prop.keySet(); for(Object obj : keys){ System.out.println(propertyFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString())); } //loading xml file now, first clear existing properties prop.clear(); InputStream is = new FileInputStream(xmlFileName); prop.loadFromXML(is); keys= prop.keySet(); for(Object obj : keys){ System.out.println(xmlFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString())); } //Now free all the resources is.close(); reader.close(); System.out.println("End of readAllKeys"); } /** * This method reads property files from file system * @param propertyFileName * @param xmlFileName * @throws IOException * @throws FileNotFoundException */ private static void readPropertyFile(String propertyFileName, String xmlFileName) throws FileNotFoundException, IOException { System.out.println("Start of readPropertyFile"); Properties prop = new Properties(); FileReader reader = new FileReader(propertyFileName); prop.load(reader); System.out.println(propertyFileName +"::db.host = "+prop.getProperty("db.host")); System.out.println(propertyFileName +"::db.user = "+prop.getProperty("db.user")); System.out.println(propertyFileName +"::db.pwd = "+prop.getProperty("db.pwd")); System.out.println(propertyFileName +"::XYZ = "+prop.getProperty("XYZ")); //loading xml file now, first clear existing properties prop.clear(); InputStream is = new FileInputStream(xmlFileName); prop.loadFromXML(is); System.out.println(xmlFileName +"::db.host = "+prop.getProperty("db.host")); System.out.println(xmlFileName +"::db.user = "+prop.getProperty("db.user")); System.out.println(xmlFileName +"::db.pwd = "+prop.getProperty("db.pwd")); System.out.println(xmlFileName +"::XYZ = "+prop.getProperty("XYZ")); //Now free all the resources is.close(); reader.close(); System.out.println("End of readPropertyFile"); } /** * This method writes Property files into file system in property file * and xml format * @param fileName * @throws IOException */ private static void writePropertyFile(String propertyFileName, String xmlFileName) throws IOException { System.out.println("Start of writePropertyFile"); Properties prop = new Properties(); prop.setProperty("db.host", "localhost"); prop.setProperty("db.user", "user"); prop.setProperty("db.pwd", "password"); prop.store(new FileWriter(propertyFileName), "DB Config file"); System.out.println(propertyFileName + " written successfully"); prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file"); System.out.println(xmlFileName + " written successfully"); System.out.println("End of writePropertyFile"); } }
当运行这段代码时,writePropertyFile 方法会在生成上述两种格式的属性文件,并將文件存储在工程的根目录下。
writePropertyFile 方法生成的两种属性文件内容:
DB.properties
#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=user db.host=localhost db.pwd=password
DB.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties><comment>DB Config XML file</comment> <entry key="db.user">user</entry><entry key="db.host">localhost</entry><entry key="db.pwd">password</entry> </properties>
需要注意的是comment元素,我们在使用prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");
这段代码时第二个参数传入的是注释内容,如果传入null,生成的xml属性文件將没有comment元素。
控制台输出内容如下:
Start of writePropertyFile DB.properties written successfully DB.xml written successfully End of writePropertyFile Start of readPropertyFileDB.properties::db.host = localhostDB.properties::db.user = userDB.properties::db.pwd = passwordDB.properties::XYZ = nullDB.xml::db.host = localhostDB.xml::db.user = userDB.xml::db.pwd = passwordDB.xml::XYZ = null End of readPropertyFile Start of readAllKeysDB.properties:: Key=db.user::value=userDB.properties:: Key=db.host::value=localhostDB.properties:: Key=db.pwd::value=passwordDB.xml:: Key=db.user::value=userDB.xml:: Key=db.host::value=localhostDB.xml:: Key=db.pwd::value=password End of readAllKeys Exception in thread "main" java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:434) at java.util.Properties.load0(Properties.java:353) at java.util.Properties.load(Properties.java:341) at com.journaldev.util.PropertyFilesUtil.readPropertyFileFromClasspath(PropertyFilesUtil.java:31) at com.journaldev.util.PropertyFilesUtil.main(PropertyFilesUtil.java:21)
这里报了空指针异常,原因是生成的文件保存在工程的根目录下面,而读取时是从classpath下读取,將上面生成的两个属性文件拷贝到src下再次运行程序即可。
我们通常会将Java应用的配置参数保存在属性文件中,Java应用的属性文件可以是一个正常的基于key-value对,以properties为扩展名的文件,也可以是XML文件.
在本案例中,將会向大家介绍如何通过Java程序输出这两种格式的属性文件,并介绍如何从classpath中加载和使用这两种属性文件。
下面是案例程序代码:
PropertyFilesUtil.java
package com.journaldev.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; public class PropertyFilesUtil { public static void main(String[] args) throws IOException { String propertyFileName = "DB.properties"; String xmlFileName = "DB.xml"; writePropertyFile(propertyFileName, xmlFileName); readPropertyFile(propertyFileName, xmlFileName); readAllKeys(propertyFileName, xmlFileName); readPropertyFileFromClasspath(propertyFileName); } /** * read property file from classpath * @param propertyFileName * @throws IOException */ private static void readPropertyFileFromClasspath(String propertyFileName) throws IOException { Properties prop = new Properties(); prop.load(PropertyFilesUtil.class.getClassLoader().getResourceAsStream(propertyFileName)); System.out.println(propertyFileName +" loaded from Classpath::db.host = "+prop.getProperty("db.host")); System.out.println(propertyFileName +" loaded from Classpath::db.user = "+prop.getProperty("db.user")); System.out.println(propertyFileName +" loaded from Classpath::db.pwd = "+prop.getProperty("db.pwd")); System.out.println(propertyFileName +" loaded from Classpath::XYZ = "+prop.getProperty("XYZ")); } /** * read all the keys from the given property files * @param propertyFileName * @param xmlFileName * @throws IOException */ private static void readAllKeys(String propertyFileName, String xmlFileName) throws IOException { System.out.println("Start of readAllKeys"); Properties prop = new Properties(); FileReader reader = new FileReader(propertyFileName); prop.load(reader); Set<Object> keys= prop.keySet(); for(Object obj : keys){ System.out.println(propertyFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString())); } //loading xml file now, first clear existing properties prop.clear(); InputStream is = new FileInputStream(xmlFileName); prop.loadFromXML(is); keys= prop.keySet(); for(Object obj : keys){ System.out.println(xmlFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString())); } //Now free all the resources is.close(); reader.close(); System.out.println("End of readAllKeys"); } /** * This method reads property files from file system * @param propertyFileName * @param xmlFileName * @throws IOException * @throws FileNotFoundException */ private static void readPropertyFile(String propertyFileName, String xmlFileName) throws FileNotFoundException, IOException { System.out.println("Start of readPropertyFile"); Properties prop = new Properties(); FileReader reader = new FileReader(propertyFileName); prop.load(reader); System.out.println(propertyFileName +"::db.host = "+prop.getProperty("db.host")); System.out.println(propertyFileName +"::db.user = "+prop.getProperty("db.user")); System.out.println(propertyFileName +"::db.pwd = "+prop.getProperty("db.pwd")); System.out.println(propertyFileName +"::XYZ = "+prop.getProperty("XYZ")); //loading xml file now, first clear existing properties prop.clear(); InputStream is = new FileInputStream(xmlFileName); prop.loadFromXML(is); System.out.println(xmlFileName +"::db.host = "+prop.getProperty("db.host")); System.out.println(xmlFileName +"::db.user = "+prop.getProperty("db.user")); System.out.println(xmlFileName +"::db.pwd = "+prop.getProperty("db.pwd")); System.out.println(xmlFileName +"::XYZ = "+prop.getProperty("XYZ")); //Now free all the resources is.close(); reader.close(); System.out.println("End of readPropertyFile"); } /** * This method writes Property files into file system in property file * and xml format * @param fileName * @throws IOException */ private static void writePropertyFile(String propertyFileName, String xmlFileName) throws IOException { System.out.println("Start of writePropertyFile"); Properties prop = new Properties(); prop.setProperty("db.host", "localhost"); prop.setProperty("db.user", "user"); prop.setProperty("db.pwd", "password"); prop.store(new FileWriter(propertyFileName), "DB Config file"); System.out.println(propertyFileName + " written successfully"); prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file"); System.out.println(xmlFileName + " written successfully"); System.out.println("End of writePropertyFile"); } }
当运行这段代码时,writePropertyFile 方法会在生成上述两种格式的属性文件,并將文件存储在工程的根目录下。
writePropertyFile 方法生成的两种属性文件内容:
DB.properties
#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=user db.host=localhost db.pwd=password
DB.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM " <properties><comment>DB Config XML file</comment><entry key="db.user">user</entry><entry key="db.host">localhost</entry> <entry key="db.pwd">password</entry></properties>
需要注意的是comment元素,我们在使用prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");
这段代码时第二个参数传入的是注释内容,如果传入null,生成的xml属性文件將没有comment元素。
控制台输出内容如下:
Start of writePropertyFile DB.properties written successfully DB.xml written successfully End of writePropertyFile Start of readPropertyFileDB.properties::db.host = localhostDB.properties::db.user = userDB.properties::db.pwd = passwordDB.properties::XYZ = nullDB.xml::db.host = localhostDB.xml::db.user = userDB.xml::db.pwd = passwordDB.xml::XYZ = null End of readPropertyFile Start of readAllKeysDB.properties:: Key=db.user::value=userDB.properties:: Key=db.host::value=localhostDB.properties:: Key=db.pwd::value=passwordDB.xml:: Key=db.user::value=userDB.xml:: Key=db.host::value=localhostDB.xml:: Key=db.pwd::value=password End of readAllKeys Exception in thread "main" java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:434) at java.util.Properties.load0(Properties.java:353) at java.util.Properties.load(Properties.java:341) at com.journaldev.util.PropertyFilesUtil.readPropertyFileFromClasspath(PropertyFilesUtil.java:31) at com.journaldev.util.PropertyFilesUtil.main(PropertyFilesUtil.java:21)
以上就是Java&Xml教程(十)XML作为属性文件使用的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

AI Hentai Generator
Menjana ai hentai secara percuma.

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas



Dalam artikel ini, kami telah menyimpan Soalan Temuduga Spring Java yang paling banyak ditanya dengan jawapan terperinci mereka. Supaya anda boleh memecahkan temuduga.

Tutorial ini menunjukkan cara memproses dokumen XML dengan cekap menggunakan PHP. XML (bahasa markup extensible) adalah bahasa markup berasaskan teks yang serba boleh yang direka untuk pembacaan manusia dan parsing mesin. Ia biasanya digunakan untuk penyimpanan data

Java 8 memperkenalkan API Stream, menyediakan cara yang kuat dan ekspresif untuk memproses koleksi data. Walau bagaimanapun, soalan biasa apabila menggunakan aliran adalah: bagaimana untuk memecahkan atau kembali dari operasi foreach? Gelung tradisional membolehkan gangguan awal atau pulangan, tetapi kaedah Foreach Stream tidak menyokong secara langsung kaedah ini. Artikel ini akan menerangkan sebab -sebab dan meneroka kaedah alternatif untuk melaksanakan penamatan pramatang dalam sistem pemprosesan aliran. Bacaan Lanjut: Penambahbaikan API Java Stream Memahami aliran aliran Kaedah Foreach adalah operasi terminal yang melakukan satu operasi pada setiap elemen dalam aliran. Niat reka bentuknya adalah

Panduan untuk TimeStamp to Date di Java. Di sini kita juga membincangkan pengenalan dan cara menukar cap waktu kepada tarikh dalam java bersama-sama dengan contoh.

Kapsul adalah angka geometri tiga dimensi, terdiri daripada silinder dan hemisfera di kedua-dua hujungnya. Jumlah kapsul boleh dikira dengan menambahkan isipadu silinder dan jumlah hemisfera di kedua -dua hujungnya. Tutorial ini akan membincangkan cara mengira jumlah kapsul yang diberikan dalam Java menggunakan kaedah yang berbeza. Formula volum kapsul Formula untuk jumlah kapsul adalah seperti berikut: Kelantangan kapsul = isipadu isipadu silinder Dua jumlah hemisfera dalam, R: Radius hemisfera. H: Ketinggian silinder (tidak termasuk hemisfera). Contoh 1 masukkan Jejari = 5 unit Ketinggian = 10 unit Output Jilid = 1570.8 Unit padu menjelaskan Kirakan kelantangan menggunakan formula: Kelantangan = π × r2 × h (4

Java ialah bahasa pengaturcaraan popular yang boleh dipelajari oleh pembangun pemula dan berpengalaman. Tutorial ini bermula dengan konsep asas dan diteruskan melalui topik lanjutan. Selepas memasang Kit Pembangunan Java, anda boleh berlatih pengaturcaraan dengan mencipta program "Hello, World!" Selepas anda memahami kod, gunakan gesaan arahan untuk menyusun dan menjalankan program, dan "Hello, World!" Pembelajaran Java memulakan perjalanan pengaturcaraan anda, dan apabila penguasaan anda semakin mendalam, anda boleh mencipta aplikasi yang lebih kompleks.

Spring Boot memudahkan penciptaan aplikasi Java yang mantap, berskala, dan siap pengeluaran, merevolusi pembangunan Java. Pendekatan "Konvensyen Lebih Konfigurasi", yang wujud pada ekosistem musim bunga, meminimumkan persediaan manual, Allo

Java Made Simple: Panduan Permulaan untuk Kuasa Pengaturcaraan Pengenalan Java ialah bahasa pengaturcaraan berkuasa yang digunakan dalam segala-galanya daripada aplikasi mudah alih hingga sistem peringkat perusahaan. Untuk pemula, sintaks Java adalah ringkas dan mudah difahami, menjadikannya pilihan ideal untuk pembelajaran pengaturcaraan. Sintaks Asas Java menggunakan paradigma pengaturcaraan berorientasikan objek berasaskan kelas. Kelas ialah templat yang menyusun data dan tingkah laku yang berkaitan bersama-sama. Berikut ialah contoh kelas Java yang mudah: publicclassPerson{privateStringname;privateintage;
