Properties store(OutputStream, String) in Java

store(OutputStream, String): This method is available in java.util.Properties class of Java.

Syntax:

void java.util.Properties.store(OutputStream out, String comments) throws IOException

This method takes two arguments. This method writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.

Parameters: Two parameters are required for this method.

out: an output stream.

comments: a description of the property list.

Throws:

1. IOException - if writing this property list to the specified output stream throws an IOException.

2. ClassCastException - if this Properties object contains any keys or values that are not Strings.

3. NullPointerException - if out is null.

Approach 1: When no exception

Java

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

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

        Properties properties = new Properties();

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

        properties.store(System.out, null);

    }
}

Output:

#Sat Mar 19 15:02:17 IST 2022

Java=Program

C++=Program

Hello=World


Approach 2: NullPointerException

Java

import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

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

        Properties properties = new Properties();

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

        OutputStream out = null;
        properties.store(out, null);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.io.Writer.<init>(Writer.java:174) at java.base/java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:126) at java.base/java.util.Properties.store(Properties.java:915)


No comments:

Post a Comment