XMLEncoder Example in Java
In this example, We will show you simple example program about, XMLEncoder Example in Java. The example program has been tested and shared in the same post.
POJO Class (Customer.class)
package com.dineshkrish; /** * * @author Dinesh Krishnan * */ public class Customer { private int id; private String name; private String phone; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", phone=" + phone + "]"; } }
Main Program (XMLEncoderExample.class)
package com.dineshkrish; import java.beans.XMLEncoder; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; /** * * @author Dinesh Krishnan * */ public class XMLEncoderExample { public static void main(String[] args) { Customer customer = new Customer(); customer.setId(101); customer.setName("Dinesh"); customer.setPhone("9876543210"); String fileName = "customer.xml"; File file = new File(fileName); try { FileOutputStream fos = new FileOutputStream(file); XMLEncoder encoder = new XMLEncoder(fos); encoder.writeObject(customer); encoder.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } } }
Output (customer.xml)
<?xml version="1.0" encoding="UTF-8"?> <java version="1.8.0_144" class="java.beans.XMLDecoder"> <object class="com.dineshkrish.Customer"> <void property="id"> <int>101</int> </void> <void property="name"> <string>Dinesh</string> </void> <void property="phone"> <string>9876543210</string> </void> </object> </java>
References
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet