JDK Timer scheduler example

JDK Timer is a simple scheduler for a specified task for repeated fixed-delay execution. To use this, you have to extends the TimerTask abstract class, override the run() method with your scheduler function. RunMeTask.java package com.mkyong.common; import java.util.TimerTask; public class RunMeTask extends TimerTask { @Override public void run() { System.out.println("Run Me ~"); } } Now, …

Read more

JavaMail API – Sending email via Gmail SMTP example

In this article, we will show you how to send an email via Gmail SMTP server. To send email in Java, we need JavaMail pom.xml <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> 1. Gmail SMTP via TLS SMTP = smtp.gmail.com Port = 587 SendEmailTLS.java package com.mkyong; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class SendEmailTLS …

Read more

Java – Convert Chinese character to Unicode with native2ascii

The native2ascii is a handy tool build-in in the JDK, which is used to convert a file with ‘non-Latin 1’ or ‘non-Unicode’ characters to ‘Unicode-encoded’ characters. Native2ascii example 1. Create a file (source.txt) Create a file named “source.txt”, put some Chinese characters inside, and save it as “UTF-8” format. 2. native2ascii Use native2ascii command to …

Read more

How to display chinese character in Eclipse console

By default, Eclipse will output Chinese or non-English characters as question marks (?) or some weird characters. This is because the Eclipse’s default console encoding is Cp1252 or ASCII, which is unable to display other non-English words. To enable Eclipse to display Chinese or other non-English characters correctly, do following : 1. In Eclipse, right …

Read more

How to Get Current Timestamps in Java

This article shows how to get the current date time or timestamps in Java. import java.sql.Timestamp; import java.time.Instant; import java.util.Date; // 2025-03-07 21:34:46.504 // Get current java.sql.Timestamp Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // 2025-03-07 21:34:46.504 // Get current java.sql.Timestamp from a Date Date date = new Date(); Timestamp timestamp2 = new Timestamp(date.getTime()); // convert Instant …

Read more

Java SHA-256 and SHA3-256 Hashing Example

In Java, we can use MessageDigest to get a SHA-256 or SHA3-256 hashing algorithm to hash a string. MessageDigest md = MessageDigest.getInstance("SHA3-256"); byte[] result = md.digest(input); This article shows how to use Java SHA-256 and SHA3-256 algorithms to generate a hash value from a given string and checksum from a file. Note The hashing is …

Read more

Java MD5 Hashing Example

The MD5, defined in RFC 1321, is a hash algorithm to turn inputs into a fixed 128-bit (16 bytes) length of the hash value. Note MD5 is not collision-resistant – Two different inputs may producing the same hash value. Read this MD5 vulnerabilities. There are many fast and secure hashing algorithms like SHA3-256 or BLAKE2; …

Read more

How to know from where a Class was loaded in Java

Here’s a tip to demonstrate how to know from where a Java Class was loaded in Java. Java Example Here’s an example to load a Java class called “Address “, package in “com.mkyong.io“, and print out the location from where this class was loaded. import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; public class App{ public static …

Read more

How to read an image from file or URL

The “javax.imageio” package is used to deal with the Java image stuff. Here’s two “ImageIO” code snippet to read an image file. 1. Read from local file File sourceimage = new File("c:\\mypic.jpg"); Image image = ImageIO.read(sourceimage); 2. Read from URL URL url = new URL("https://mkyong.com/image/mypic.jpg"); Image image = ImageIO.read(url); ImageIO Example In this example, you …

Read more

How to decompress serialized object from a Gzip file

In last section, you learn about how to compress a serialized object into a file, now you learn how to decompress it from a Gzip file. FileInputStream fin = new FileInputStream("c:\\address.gz"); GZIPInputStream gis = new GZIPInputStream(fin); ObjectInputStream ois = new ObjectInputStream(gis); address = (Address) ois.readObject(); GZIP example In this example, you will decompress a compressed …

Read more

How to compress serialized object into file

In last section, you learn about how to write or serialized an object into a file. In this example , you can do more than just serialized it , you also can compress the serialized object to reduce the file size. The idea is very simple, just using the “GZIPOutputStream” for the data compression. FileOutputStream …

Read more

What is the different between Set and List

Set and List explanation Set – Stored elements in unordered or shuffles way, and does not allow duplicate values. List – Stored elements in ordered way, and allow duplicate values. Set and List Example import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SetAndListExample { public static void main( String[] args ) { System.out.println("List …

Read more

How to find files with the file extension in Java

This article shows how to Java 8 Files.walk to walk a file tree and stream operation filter to find files that match a specific file extension from a folder and its subfolders. // find files matched `png` file extension from folder C:\\test try (Stream<Path> walk = Files.walk(Paths.get("C:\\test"))) { result = walk .filter(p -> !Files.isDirectory(p)) // …

Read more

Java Properties file examples

Normally, Java properties file is used to store project configuration data or settings. In this tutorial, we will show you how to read and write to/from a .properties file. Properties prop = new Properties(); // set key and value prop.setProperty("db.url", "localhost"); prop.setProperty("db.user", "mkyong"); prop.setProperty("db.password", "password"); // save a properties file prop.store(outputStream, ""); // load a …

Read more

How to get a Java Class Object

As far as i know, there are 4 ways to get the Java Class object. 1. “.class” Class cls = Address.class; 2. object.getClass() Address address = new Address(); Class cls = address.getClass(); 3. Class.forName() Class cls = Class.forName("com.mkyong.io.Address"); 4. ClassLoader.loadClass() ClassLoader cl = ClassLoader.getSystemClassLoader(); Class cls = cl.loadClass("com.mkyong.io.Address");

How to make a Java exe file or executable JAR file

In this tutorial, we will show you how to create a executable JAR – When you double click on it, it runs the defined main class in manifest file. 1. AWT Example Create a simple AWT Java application, just display label and print out some funny characters ~ AwtExample.java package com.mkyong.awt; import java.awt.Frame; import java.awt.Label; …

Read more

How to compare dates in Java

This article shows few examples to compare two dates in Java. Updated with Java 8 examples. 1. Compare two date 1.1 Date.compareTo 1.2 Date.before(), Date.after() and Date.equals() 1.3 Check if a date is within a certain range 2. Compare two calendar 3. Compare two date and time (Java 8) 3.1 Compare two LocalDate 3.2 Compare …

Read more

Jar manifest error – java.io.IOException: invalid header field

Often times, this error is causing by the mismatch order between “m” and “f” Jar options. For example, jar -cvfm manifest.txt example.jar com/mkyong/awt/*.class The above command will causing the following error : java.io.IOException: invalid header field at java.util.jar.Attributes.read(Attributes.java:406) at java.util.jar.Manifest.read(Manifest.java:199) at java.util.jar.Manifest.<init>(Manifest.java:69) at sun.tools.jar.Main.run(Main.java:150) at sun.tools.jar.Main.main(Main.java:1044) Did you spot the error? The “m” and “manifest” …

Read more

Java StringTokenizer examples

In Java, we use StringTokenizer to split a string into multiple tokens. Note The StringTokenizer is a legacy class, try the split method of String, read this How to split a string in Java. 1. StringTokenizer examples 1.1 By default, the StringTokenizer uses default delimiters: space, tab, newline, carriage-return, and form-feed characters to split a …

Read more

How to read and write an image in Java

In Java, we can use the javax.imageio.ImageIO class to read and write an image. 1. Read an image Read an image from a file. BufferedImage image = ImageIO.read(new File("c:\\test\\image.png")); Read an image from an URL. BufferedImage image = ImageIO.read(new URL("https://example.com/image.png")); 2. Write or save an image Write or save an image in different image formats. …

Read more

The Java Archive Tool (JAR) Examples

Here’s the project structure. /workspace/test/classes/com/mkyong/awt/AwtExample.class /workspace/test/classes/com/mkyong/awt/AwtExample2.class /workspace/test/classes/com/mkyong/awt/AwtExample3.class /workspace/test/classes/manifest.txt P.S Assume you are in “/workspace/test/classes/“ 1. Create a jar file -c create new archive -v generate verbose output on standard output -f specify archive file name 1.1 Create a Jar file which include AwtExample.class only. jar -cvf test.jar com/mkyong/awt/AwtExample.class 1.2 Create a Jar file which include …

Read more

How to list out all system drives in your system

File.listRoots() will list out all the available file system roots / drives in your current system. Example package com.mkyong.io; import java.io.File; public class App{ public static void main (String args[]) { File[] rootDrive = File.listRoots(); for(File sysDrive : rootDrive){ System.out.println("Drive : " + sysDrive); } } } Output Drive : A:\ Drive : C:\ Drive …

Read more

Java – How to generate serialVersionUID

This article shows you a few ways to generate the serialVersionUID for serialization class. 1. serialver JDK has a built-in command serialver to generate a serialVersionUID automatically. In this example, we use serialver to generate a serialVersionUID for an Address class. Terminal $ serialver Address Address: static final long serialVersionUID = -687991492884005033L; 2. Eclispe IDE …

Read more

How to load classes which are not in your classpath

In certain scenario, you may need to load some classes which are not in your classpath. Java Example Assume folder “c:\\other_classes\\” is not in your project classpath, here’s an example to show how to load a Java class from this folder. The code and comments are self-explanatory. import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; …

Read more

How to add a manifest into a Jar file

In Java, you can use manifest file to define application’s entry point, adding classpath or package version for a JAR file. In this short tutorial , we will show you how to add a custom manifest file into a Jar file. 1. Project Structure Assume this is your project folder structure /workspace/test/classes/com/mkyong/awt/AwtExample.class /workspace/test/classes/manifest.txt 2. Jar …

Read more

How to run a Java application with no main method

Java application usually required a main() method as entry point to run it. Here’s an example by using static initializer to run a Java application even without the main() method. P.S The static initializer is called while the Java class is loaded. This is for fun only, do not use this example in real environment …

Read more

How to print out the current project classpath

Java’s “SystemClassLoader” can use to pint out the current project classpath , indirectly display the library dependency as well. Example package com.mkyong.io; import java.net.URL; import java.net.URLClassLoader; public class App{ public static void main (String args[]) { ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader)cl).getURLs(); for(URL url: urls){ System.out.println(url.getFile()); } } } Output /E:/workspace/HibernateExample/target/test-classes/ /E:/workspace/HibernateExample/target/classes/ /D:/maven/repo/antlr/antlr/2.7.7/antlr-2.7.7.jar …

Read more

How to get the standard input in Java

Note This post is duplicated, please refer to this – 3 ways to read input from console in Java. A quick example to show you how to read the standard input in Java. package com.mkyong.pageview; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) { BufferedReader br = null; …

Read more

How to assign file content into a variable in Java

Most people will read the file content and assign to StringBuffer or String line by line. Here’s another trick that may interest you – how to assign whole file content into a variable with one Java’s statement, try it 🙂 Example In this example, you will use DataInputStreamto convert all the content into bytes, and …

Read more

How to traverse a directory structure in Java

In this example, the program will traverse the given directory and print out all the directories and files absolute path and name one by one. Example package com.mkyong.io; import java.io.File; public class DisplayDirectoryAndFile{ public static void main (String args[]) { displayIt(new File("C:\\Downloads")); } public static void displayIt(File node){ System.out.println(node.getAbsoluteFile()); if(node.isDirectory()){ String[] subNote = node.list(); for(String …

Read more

How to open a PDF file in Java

In this article, we show you two ways to open a PDF file with Java. 1. rundll32 – Windows Platform Solution In Windows, you can use “rundll32” command to launch a PDF file, see example : package com.mkyong.jdbc; import java.io.File; //Windows solution to view a PDF file public class WindowsPlatformAppPDF { public static void main(String[] …

Read more

How to clear / delete the content of StringBuffer()

The StringBuffer is always been using for the String concatenation. However this class didn’t provide a method to clear the existing content. Why there are no clear() function? You can use the delete(int start, int end) as dirty trick : sb.delete(0, sb.length()); 1 . Example package com.mkyong.io; public class App{ public static void main (String …

Read more

How to convert HTML to Javascript (.js) in Java

For some security reasons, you may need to convert your HTML file into Javascript (js) file, and display the JS file instead of the HTML file directly. The concept is quite simple – using the document.write HTML <h1>Convert HTML to Javascript file</h1> Javascript (js) document.write(‘<h1>Convert HTML to Javascript file</h1>’); 1. Test.html Create a simple HTML …

Read more