Java – Load Properties from a XML file

Properties from XML file can be read using loadFromXML() option

 
package com.pwn.property;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class LoadPropertyFromXML {

	public static void main(String[] args) {
		// make new properties instance to load the file into
		Properties prop = new Properties();
		// check to make sure the file exists
		File file = new File("c://install//userdetails.xml");
		if (file.exists()) {
			// load the file
			try {
				prop.loadFromXML(new FileInputStream(file));
			} catch (InvalidPropertiesFormatException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// print out all the properties
			for (String name : prop.stringPropertyNames()) {
				System.out
						.println(name + "=" + prop.getProperty(name));
			}
		} else {
			System.err.println("Error: No file found : ");
		}

	}

}

name=Naveen
country=US

Java – Saving Properties as XML

Using storeToXML() option Property files can be stored as XML.

 
package com.pwn.property;

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

public class SavePropertyAsXML {

	public static void main(String[] args) {
		// make new instance of properties
		Properties prop = new Properties();
		// set the property values
		prop.setProperty("name", "Naveen");
		prop.setProperty("country", "US");

		// check to see if the file already exists
		File file = new File("c://install//userdetails.xml");
		if (!file.exists()) {
			// save the properties
			try {
				file.createNewFile();
				prop.storeToXML(new FileOutputStream(file),
						"testing properties with xml");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>testing properties with xml</comment>
<entry key="name">Naveen</entry>
<entry key="country">US</entry>
</properties>

Java – Loading Property File

The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of
Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods to get data
from properties file and store data into properties file.

Use following sample applicaiton to load a properties file bundled :

 
package com.pwn.property;

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

public class LoadingProperty {
	
	/*user.properties
	name=Naveen
	country=US*/

	public static void main(String[] args) {
		try (InputStream bundledResource = LoadingProperty.class
				.getResourceAsStream("user.properties")) {
			Properties userProperties = new Properties();
			userProperties.load(bundledResource);
			System.out.println("username from property file "
					+ userProperties.get("name"));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
username from property file Naveen

Java – Iterator, Iterable

Iterator

An Iterator is an interface which allows iterating over collection
It provides hasNext() and next() methods to iterate as shown below –

Iterator lists= Arrays.asList("A","B","C").iterator();
		while(lists.hasNext()) {
			System.out.println(lists.next());
		}

Iterable

An Iterable represents a collection which can be traversed.
Implementing the Iterable() interface allows an object to make use of a for-each loop.

package com.pwn.collection;
import java.util.Iterator;

public class CustomIterable {

	public static void main(String[] args) {
		System.out.println("Alphabet List below ");
		for (char c : new Alphabet()) {
			System.out.println(c);
		}
	}
}

class Alphabet implements Iterable<Character> {
	@Override
	public Iterator<Character> iterator() {
		return new Iterator<Character>() {
			char letter = 'a';

			@Override
			public boolean hasNext() {
				return letter <= 'z';
			}

			@Override
			public Character next() {
				return letter++;
			}

			@Override
			public void remove() {
				throw new 
                                UnsupportedOperationException(
		            "Doesn't make sense to remove a letter");
			}
		};
	}
}
Alphabet List below 
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

Java – Execute Javascipt

Nashorn is a JavaScript engine developed in Java by Oracle, and has been released with Java 8. Nashorn allows embedding Javascript in Java applications via JSR-223 and allows to develop standalone Javascript applications, and it provides better runtime performance and better compliance with the ECMA normalized Javascript specification.

Java 8 introduces new command-line tool called jjs, for executing JavaScript. It can be found in the bin/ folder of a JDK installation along with the well-known java, javac, or jar tools.

The jjs tool accepts a list of JavaScript source code files as arguments.

Please note this program run in JDK version 8 or greater.

 
package com.pwn.js;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ExecuteJS {

	public static void main(String[] args) {
		// Obtain an instance of the JavaScript engine
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("nashorn");
		/*
		 * hello.js source code 
		 * var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
		 * var evenNumbers = array.filter(function(i) { return i % 2 == 0; });
		 * print('Output from JS file ',evenNumbers);
		 */

		// Load and execute a script from the file 'hello.js'
		try {
			engine.eval(
					new FileReader(new File("c://install/hello.js")));
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (ScriptException ex) {
			ex.printStackTrace();
		}

	}

}

Output from JS file  2,4,6,8,10