How to read and write key/value pairs inside .ini file JAVA (XML store)


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

Use the following code to store key and values inside a .ini file using Java Environment.

This program demonstrates the use of .ini file by implementing regular txt and XML storing methods.

To use the .ini file in this program you should create a folder called ini under the root folder of your project and you should put a file called example.ini under this folder.

/*
 * How to read and write value for an .ini
 * file on Java Environment Example
 */
package inifilereaderwriterexample;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @author tunatore
 */
public class INIFileReaderWriterExample {

public static void main(String[] args) {

//appending to the file
//appending file functionality can be modified by changing true and false parameter of
//FileOutputStream object if the parameter is set to false
//it will remove all content of ini file
//of it is set to true it will append the new key/value pairs
INIFileReaderWriterExample.writeKeyValuePairsINIFile("java", "James Gosling");
INIFileReaderWriterExample.writeKeyValuePairsINIFile("linux", "Linus Torvalds");
INIFileReaderWriterExample.writeKeyValuePairsINIFile("microsoft", "Bill Gates");

INIFileReaderWriterExample.readINIFile();

Map<String, String> keyValueMapXML = new HashMap<String, String>();
keyValueMapXML.put("book1", "How to program Java");
keyValueMapXML.put("book2", "PL/SQL programming best practices");
keyValueMapXML.put("book3", "ORACLE Performance Tuning");

//storing key values a XML inside .ini file
INIFileReaderWriterExample.writeKeyValuePairsINIFileXML(keyValueMapXML);

//reading the XML key value pairs inside .ini file
INIFileReaderWriterExample.readINIFileXML();
}
private static void readINIFile() {

try {
Properties props = new Properties();
//loading the .ini file under ini folder
props.load(new FileInputStream(System.getProperty("user.dir")+"\\ini\\"+"example.ini"));
System.out.println("access with the key java = >> " + props.getProperty("java"));
System.out.println("access with the key linux = >> " + props.getProperty("linux"));
System.out.println("access with the key microsoft = >> " + props.getProperty("microsoft"));
props.list(System.out);

} catch (Exception ex) {
ex.printStackTrace();
}

}

private static void readINIFileXML() {

try {
Properties props = new Properties();
//loading the .ini file under ini folder
props.load(new FileInputStream(System.getProperty("user.dir")+"\\ini\\"+"example.ini"));
props.loadFromXML(new FileInputStream(System.getProperty("user.dir")+"\\ini\\"+"example.ini"));
System.out.println(props.getProperty("book3"));
System.out.println(props.getProperty("book2"));
System.out.println(props.getProperty("book1"));
} catch (Exception ex) {
ex.printStackTrace();
}

}

private static void writeKeyValuePairsINIFile(String key,String value) {

try {
Properties props = new Properties();
//loading the .ini file under ini folder
props.load(new FileInputStream(System.getProperty("user.dir") + "\\ini\\" + "example.ini"));
props.setProperty(key, value);
props.store(new FileOutputStream(System.getProperty("user.dir")
+ "\\ini\\" + "example.ini", true), "Here you can enter comment");
} catch (Exception ex) {
ex.printStackTrace();
}

}
private static void writeKeyValuePairsINIFileXML (Map<String, String> keyValuePairs) {

try {
Properties props = new Properties();
//loading the .ini file under ini folder
props.load(new FileInputStream(System.getProperty("user.dir") + "\\ini\\" + "example.ini"));
Iterator mapInterator = keyValuePairs.entrySet().iterator();
while (mapInterator.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry) mapInterator.next();
props.setProperty(pairs.getKey(), pairs.getValue());
}
props.storeToXML(new FileOutputStream(System.getProperty("user.dir")
+ "\\ini\\" + "example.ini", false), "Here you can enter comment");
} catch (Exception ex) {
ex.printStackTrace();
}

}

}

Output of the program

run:
access with the key java = >> James Gosling
access with the key linux = >> Linus Torvalds
access with the key microsoft = >> Bill Gates
— listing properties —
java=James Gosling
linux=Linus Torvalds
microsoft=Bill Gates
ORACLE Performance Tuning
PL/SQL programming best practices
How to program Java
BUILD SUCCESSFUL (total time: 0 seconds)

XML inside example.ini file

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Here you can enter comment</comment>
<entry key="java">James Gosling</entry>
<entry key="book3">ORACLE Performance Tuning</entry>
<entry key="microsoft">Bill Gates</entry>
<entry key="linux">Linus Torvalds</entry>
<entry key="book2">PL/SQL programming best practices</entry>
<entry key="book1">How to program Java</entry>
</properties>

Source code of the program

Advertisements

How to run queries on Microsoft Access mdb file using Java


If you need to run queries on Microsoft Access database file (mdb) using JDBC(odbc)  driver use the following code snippets;

MSAccessUtil class

/*
 * tunatore
 */
package msaccessjavaapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *
 * @author tunatore
 */
public class MSAccessUtil {

//this class uses sun.jdbc.odbc.JdbcOdbcDriver
public static Connection connectToAccess () {
Connection connection = null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dbConnectionString = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
//to use on Microsoft Operating System use the following path access method
String accessFileLocation =  MSAccessUtil.class.getResource("sampledb.mdb").getPath().substring(1).replace("/", "\\");
System.out.println("location of mdb file ==> " + accessFileLocation);
String URL = dbConnectionString + accessFileLocation;
connection = DriverManager.getConnection(URL);
}catch(Exception ex) {
ex.printStackTrace();
}
return connection;
}
public static void closeConnecion(Connection conn) {

try {
if(conn !=null) {
conn.commit();
conn.close();
}

} catch (Exception ex) {
ex.printStackTrace();
}

}
public static void runSELECTQueryOnAccess(Connection conn, String SQL) {

Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while(rs.next()) {
System.out.println(rs.getString("firstColumn")
+ " " + rs.getString("secondColumn")
+ " " + rs.getString("thirdColumn"));
}
rs.close();
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void runINSERT_OR_DELETEQueryOnAccess(Connection conn, String SQL) {

Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(SQL);
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

}

MSAccessJavaApplication class

package msaccessjavaapplication;
import java.sql.Connection;

public class MSAccessJavaApplication {

public static void main(String[] args) {

Connection conn = MSAccessUtil.connectToAccess();
MSAccessUtil.runINSERT_OR_DELETEQueryOnAccess(conn,"DELETE FROM SAMPLETABLE");
for (int i = 0; i < 10; i++) {
 String SQL =</em> "INSERT INTO SAMPLETABLE VALUES('"+ i + "','" + i + "','" + i + "')";
 MSAccessUtil.runINSERT_OR_DELETEQueryOnAccess(conn, SQL);
 }
 MSAccessUtil.runSELECTQueryOnAccess(conn, "SELECT * FROM SAMPLETABLE");
MSAccessUtil.closeConnecion(conn);

}
 }

Output of the program;
run:
location of mdb file ==> C:\Users\tunatore\Desktop\development\MSAccessJavaApplication\build\classes\msaccessjavaapplication\sampledb.mdb
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
BUILD SUCCESSFUL (total time: 0 seconds)

Download full source (sampledb.mdb file included)

How to use Vector collection implementation in Java environment


Vector collection is an implementation of the List interface in Java Collection Framework.
Vector is also a synchronized collection that could be used in thread safe applications.
Because of that it has slower performance than the ArrayList implementation of the List Interface.

Here is an example program for the usage of Vector collection class in Java


/*
 *How to use a Vector implementation of Java Collection Framework
 */

package vectorexample;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author tunatore
 */

public class VectorExample {

public static void main(String[] args) {

System.out.println("==========VECTOR EXAMPLE==========");
List<String> vectorOne = new Vector<String>();        
vectorOne.add("this is the first element for the VectorOne");
vectorOne.add("this is the second element for the VectorOne");
vectorOne.add("this is the third element for the VectorOne");

Vector<String> vectorTwo = new Vector<String>();
vectorTwo.add("this is the first element for the vectorTwo");
vectorTwo.add("this is the second element for the vectorTwo");

System.out.println("The size of the vectorOne --> " + vectorOne.size());
System.out.println("The size of the vectorTwo --> " + vectorTwo.size());

System.out.println("==========Getting the elements inside vectorTwo==========");

for (Iterator<String> it = vectorTwo.iterator(); it.hasNext();) {
String element = it.next();
System.out.println(element);
}

System.out.println("==========Testing an element existince in vectorTwo==========");
System.out.println("Exist or Not --> " + vectorTwo.contains("this is the second element for the vectorTwo"));

System.out.println("==========Removing an element using index remove(i) in vectorTwo==========");
vectorTwo.remove(1); // 1 refers to the second element in vectorTwo

System.out.println("==========Testing againg an element existince in vectorTwo==========");
System.out.println("Exist or Not --> " + vectorTwo.contains("this is the second element for the vectorTwo"));

System.out.println("==========Adding two more elements in vectorTwo==========");
vectorTwo.add("this is the second element for the vectorTwo");
vectorTwo.add("this is the third element for the vectorTwo");

System.out.println("==========Getting the first element of vectorTwo==========");
System.out.println("The first element ==> " + vectorTwo.firstElement());

System.out.println("==========Getting the last element of VectorOne==========");
System.out.println("The last element ==> " + vectorTwo.lastElement());
}
}

The Output for the program;

run:
==========VECTOR EXAMPLE==========
The size of the vectorOne –> 3
The size of the vectorTwo –> 2
==========Getting the elements inside vectorTwo==========
this is the first element for the vectorTwo
this is the second element for the vectorTwo
==========Testing an element existince in vectorTwo==========
Exist or Not –> true
==========Removing an element using index remove(i) in vectorTwo==========
==========Testing againg an element existince in vectorTwo==========
Exist or Not –> false
==========Adding two more elements in vectorTwo==========
==========Getting the first element of vectorTwo==========
The first element ==> this is the first element for the vectorTwo
==========Getting the last element of VectorOne==========
The last element ==> this is the third element for the vectorTwo
BUILD SUCCESSFUL (total time: 0 seconds)

Download Source

How to send an e-mail using Java Mail API (Swing Desktop Application using Google’s SMTP Server)


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

To use the Java Mail API inside your project, you should download the latest Java Mail API jar from the following link;

Java Mail API 1.4.4 Download

You should have a reference for the mail.jar inside the project and you can use the following source code for sending e-mail from Java Programs.


private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {

boolean isSent = true;

try {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", txtfrom.getText()); //such as abc@gmail.com
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", txthostName.getText());   //use smtp.google.com for Google
        properties.put("mail.smtp.user", txtfrom.getText()); //such as abc@gmail.com
        properties.put("mail.smtp.port", txtPort.getText()); //use 465 for Google's SMTP server
        properties.put("mail.smtp.socketFactory.port", txtPort.getText()); //use 465 for Google's SMTP server
        properties.put("mail.smtp.starttls.enable","true");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");

        Authenticator mailAuthenticator = new MailAuthenticator();
        Session mailSession = Session.getDefaultInstance(properties,mailAuthenticator);
        Message message = new MimeMessage(mailSession);

        InternetAddress fromAddress = new InternetAddress(txtfrom.getText());
        InternetAddress toAddress = new InternetAddress(txtto.getText());

        message.setFrom(fromAddress);
        message.setRecipient(RecipientType.TO, toAddress);
        //you can use RecipientTypes such as
        //RecipientType.TO
        //RecipientType.BCC
        //RecipientType.CC
        //RecipientType.NEWSGROUPS
        message.setSubject(txtsubject.getText());
        message.setText(txtcontent.getText());

        Transport.send(message);

} catch (Exception e) {
     lblInfo.setText("ERROR:" + e.getMessage());
     isSent = false;
}

     if(isSent == true) {
     sendButton.setEnabled(false);
     lblInfo.setText("Your e-mail has been sent.");
}

}

private class MailAuthenticator extends javax.mail.Authenticator {

private PasswordAuthentication authentication = null;
private String username;
private String password;

public MailAuthenticator() {
this.username = txtusername.getText();
this.password = new String(txtPassword.getPassword());
this.authentication = new PasswordAuthentication(username,password);
}

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

The following program uses Authentication before sending e-mails.

The screenshot for the program;

Download Source of the Program (Swing Java Mail API example program)

After downloading the program, you should  click on the .jar file under the following directory

Desktop\SendEmailJavaDesktopExample\SendEmailJavaDesktopExample\dist\SendEmailJavaDesktopExample.jar

How to monitor file changes using java.nio JDK 7 API (WatcherService example)


If you want to monitor files under a directory, you can use the following source code.

This program will monitor files for the events such as MODIFY,CREATE and DELETE.

(Don’t forget this program requires JDK 7.0)

package watcherserviceexamplejdk7;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKind.*;

/**
*
* @author tunatore
*/
public class WatcherServiceExampleJDK7 {

public static void main(String[] args) throws IOException, InterruptedException {
monitorFilesInDirectory("C:\\directoryname");
}

public static void monitorFilesInDirectory(String directory) {

try {
//create a WatcherService object for monitoring directories
WatchService watchService = FileSystems.getDefault().newWatchService();
//getting the path object for the directory given by users
Path path = Paths.get(directory);
//register the events to be notified by the program
path.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
while (true) {
//infinite loop will take events
WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//getting the type of the event
WatchEvent.Kind<?> kind = watchEvent.kind();
//getting the file name from the WatchEvent object
Path file = (Path) watchEvent.context();
System.out.println("Filename --> " + file + " Event type --> " + kind.name());
}
//reset the current event and wait for other events
key.reset();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Here is an example output for the program;

processes taken in the following order

1. Created a file named abc.txt (under the directory)
2. Modified abc.txt

3. Deleted abc.txt file

Filename –> New Text Document.txt Event type –> ENTRY_CREATE
Filename –> New Text Document.txt Event type –> ENTRY_DELETE
Filename –> abc.txt Event type –> ENTRY_CREATE

Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_DELETE

BUILD STOPPED (total time: 1 minute 57 seconds)

Download Source Code

How to use Java Reflection API example


Reflection API allows developers to manipulate the internal properties of the class such as fields and methods. It also allows developers to call private methods in other packages or use any private fields defined in different packages.

Lets examine the following code and the output of the program;

First create a DummyClass.javaclas

package javareflectionexample;

public class DummyClass {

private int value1 = 0;
private String value2 = "value2 content";
private Integer value3 = 1;
private boolean value4 = true;
private int value5 = 5;

public void add(int a,int b){
System.out.println("a+b --> " + (a+b));
}

public void minus(int a,int b) {
System.out.println("a-b --> " + (a-b));
}

public void divide(int a,int b) throws ArithmeticException {
System.out.println("a/b --> " + (a/b));
}
public void adding(Integer a,Integer b, Integer c, Double d) {
System.out.println("a + b + c + d --> " + (a + b + c + d));
}
private void printValues() {
System.out.println("value1 --> " + value1);
System.out.println("value2 --> " + value2);
System.out.println("value3 --> " + value3);
System.out.println("value4 --> " + value4);
System.out.println("value5 --> " + value5);
}

}

And create main program MainProgram.java

package javareflectionexample;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MainProgram {

public static void main(String[] args) {

try {

Class clazz = Class.forName("javareflectionexample.DummyClass");
Method[] methods = clazz.getDeclaredMethods();

//printing all methods inside javareflectionexample.DummyClass including
//private methods

System.out.println("START PRINTING METHOD NAMES\n");

for (int i = 0; i < methods.length; i++) {

Method method = methods[i];
System.out.println("[method name] --> " +">method.getName()
+ " [long desc] --> " + method.toString());

}

//Getting all Parameter types for all methods
//includes private methods

//if you want to get only public methods and methods inside Object class
//use claz.getMethods()

System.out.println("\nSTART PRINTING PARAMETER NAMES AND RETURN TYPES");

for (int i = 0; i < methods.length; i++) {

System.out.println("\n[method " + i + " name] --> " +methods[i].getName()
+ " [return type] --> " +methods[i].getReturnType());

for (int j = 0; j < methods[i].getParameterTypes().length; j++) {
Class parameter = methods[i].getParameterTypes()[j];
System.out.println(" [parameter " + j + " type] --> " +parameter.getName());
}

}

System.out.println("\nSTART PRINTING FIELD NAMES AND VALUES\n");

//getting all fields including private ones inside DummyClass
Field fields[] = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++){
fields[i].setAccessible(true);
System.out.println("[field " + i + " name] -->" +fields[i].getName()
+ " [field " + i + " value] --> " + fields[i].get(clazz.newInstance()));
}

//calling all private methods inside DummyClass
System.out.println("\nSTART CALLING ONLY PRIVATE METHODS\n");

for (int i = 0; i < methods.length; i++) {
if (methods[i].getModifiers() == Modifier.PRIVATE) {
System.out.println("[method " + i + " name] --> " +methods[i].getName()
+ " [modifier] --> " + "Modifier.PRIVATE");
methods[i].setAccessible(true);
//SYNTAX for calling a method with parameters
//methods[i].invoke(obj, args);
//this will call private void printValues()
methods[i].invoke(clazz.newInstance());
}
}

} catch (Exception ex) {
Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

Output of the program;

START PRINTING METHOD NAMES

[method name] –> minus [long desc] –> public void javareflectionexample.DummyClass.minus(int,int)
[method name] –> adding [long desc] –> public void javareflectionexample.DummyClass.adding(java.lang.Integer,java.lang.Integer, java.lang.Integer,java.lang.Double)
[method name] –> printValues [long desc] –> private void javareflectionexample.DummyClass.printValues()
[method name] –> add [long desc] –> public void javareflectionexample.DummyClass.add(int,int)
[method name] –> divide [long desc] –> public void javareflectionexample.DummyClass.divide(int,int) throws java.lang.ArithmeticException

START PRINTING PARAMETER NAMES AND RETURN TYPES

[method 0 name] –> minus [return type] –> void
[parameter 0 type] –> int
[parameter 1 type] –> int

[method 1 name] –> adding [return type] –> void
[parameter 0 type] –> java.lang.Integer
[parameter 1 type] –> java.lang.Integer
[parameter 2 type] –> java.lang.Integer
[parameter 3 type] –> java.lang.Double

[method 2 name] –> printValues [return type] –> void

[method 3 name] –> add [return type] –> void
[parameter 0 type] –> int
[parameter 1 type] –> int

[method 4 name] –> divide [return type] –> void
[parameter 0 type] –> int
[parameter 1 type] –> int

START PRINTING FIELD NAMES AND VALUES

[field 0 name] –>value1 [field 0 value] –> 0
[field 1 name] –>value2 [field 1 value] –> value2 content
[field 2 name] –>value3 [field 2 value] –> 1
[field 3 name] –>value4 [field 3 value] –> true
[field 4 name] –>value5 [field 4 value] –> 5

START CALLING ONLY PRIVATE METHODS

[method 2 name] –> printValues [modifier] –> Modifier.PRIVATE
value1 –> 0
value2 –> value2 content
value3 –> 1
value4 –> true
value5 –> 5

Download Eclipse Project Source

How to use Static Blocks and Instance Initializers in Java


Examine the following code to understand how Static Blocks and Instance Initializers work in Java Environment

package staticblocksstaticinitializerexample;

/**
 *
 * @author tunatore
 */

//SYNTAX
// public class CLASS{
//
//    static{
//    ….
//    }
//    {
//    …
//    }
//    //variables
//    //methods
//}

public class AnObject {

/**
     * static blocks and static initializer example
     */

static int value;

//runs only once when the class first loaded by Java JVM
    //static block
static {    
value = 100;
System.out.println(Called by JVM only once! value is –> + value);
}

//this Instance Initializer runs every time when a new instance created

value++;
System.out.println(“Every time runs when a new instance is created!”);
}
public static void main(String[] args) {

{
  //this is not an Instance Initializer
            //this block runs only once as a regular statement
System.out.println(“This is not an Instance Initializer”);

}

AnObject object = new AnObject();
System.out.println(“value is –> “ + object.value);

AnObject object2 = new AnObject();
System.out.println(“value is –> “ + object2.value);

AnObject object3 = new AnObject();
System.out.println(“value is –> “ + object3.value);

}

}

Output of the program

run:
Called by JVM only once! value is –> 100
This is not an Instance Initializer
Every time runs when a new instance is created!
value is –> 101
Every time runs when a new instance is created!
value is –> 102
Every time runs when a new instance is created!
value is –> 103
BUILD SUCCESSFUL (total time: 1 second)

Download Source