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 define auto complete abbreviation for NetBeans (System.out.println() example)


If you want to define a short cut template for the System.out.println() method of Java

You can do it using Code Templates in NetBeans IDE.

Just follow the following path to open Code Template window on NetBeans

Click on Tools>Options

From here, choose the Code Templates section and Click New button on the right

Enter an Abbreviation for System.out.println(); such as sys

and press Enter

Inside the Expanded Text section you should write ${no-indent}System.out.println(“”);

Select code complete method from Expand Template on List such as Enter, Tab…and press OK

Now if you choose Enter for the expand method and if you write on IDE only

sys and press Enter key then Netbeans will complete the code like;

System.out.println(“”);

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