Properties loadFromXML(InputStream) in Java

loadFromXML(InputStream): This method is available in java.util.Properties class of Java.

Syntax:

void java.util.Properties.loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException

This method takes one argument. This method loads all of the properties represented by the XML document on the specified input stream into this properties table.

Parameters: One parameter is required for this method.

in: the input stream from which to read the XML document.

Throws:

1. IOException - if reading from the specified input stream results in an IOException.

2. UnsupportedEncodingException - if the document's encoding declaration can be read and it specifies an encoding that is not supported.

3. InvalidPropertiesFormatException - Data on the input stream does not constitute a valid XML document with the mandated document type.

4. NullPointerException - if in is null.

Approach 1: When no exception

Java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesloadFromXML {
    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();

        properties.put("Hello", "World");
        properties.put("C++", "Program");
        properties.put("Java", "Program");

        FileOutputStream fileOutputStream =
new FileOutputStream("hello.xml");
        FileInputStream in =
new FileInputStream("hello.xml");

        properties.storeToXML(fileOutputStream, null);

        properties.loadFromXML(in);

        properties.list(System.out);

    }
}

Output:

-- listing properties --

Java=Program

C++=Program

Hello=World


Approach 2: NullPointerException 

Java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesloadFromXML {
    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();

        properties.put("Hello", "World");
        properties.put("C++", "Program");
        properties.put("Java", "Program");

        FileOutputStream fileOutputStream =
new FileOutputStream("hello.xml");
        FileInputStream in = null;

        properties.storeToXML(fileOutputStream, null);

        properties.loadFromXML(in);

        properties.list(System.out);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Properties.loadFromXML(Properties.java:978)



No comments:

Post a Comment