How to construct a file path in Java

In this tutorial, we will show you three Java examples to construct a file path : File.separator or System.getProperty(“file.separator”) (Recommended) File file = new File(workingDir, filename); (Recommended) Create the file separator manually. (Not recommend, just for fun) 1. File.separator Classic Java example to construct a file path, using File.separator or System.getProperty(“file.separator”). Both will check the …

Read more

How to get the temporary file path in Java

In Java, we can use System.getProperty("java.io.tmpdir") to get the default temporary file location. For Windows, the default temporary folder is %USER%\AppData\Local\Temp For Linux, the default temporary folder is /tmp 1. java.io.tmpdir Run the below Java program on a Ubuntu Linux. TempFilePath1 package com.mkyong.io.temp; public class TempFilePath1 { public static void main(String[] args) { String tmpdir …

Read more

How to write to file in Java – FileOutputStream

In Java, FileOutputStream is a bytes stream class that’s used to handle raw binary data. To write the data to file, you have to convert the data into bytes and save it to file. See below full example. package com.mkyong.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample { public static void main(String[] args) …

Read more

How to set the file permission in Java

In Java, file permissions are very OS specific: *nix , NTFS (windows) and FAT/FAT32, all have different kind of file permissions. Java comes with some generic file permission to deal with it. Check if the file permission allow : file.canExecute(); – return true, file is executable; false is not. file.canWrite(); – return true, file is …

Read more

How to determine a prime number in Java

A very important question in mathematics and security is telling whether a number is prime or not. This is pretty useful when encrypting a password. In this tutorial, you will learn how to find whether a number is prime in simple cases. Trivial Cases We learned numbers are prime if the only divisors they have …

Read more

Quartz 1.6 scheduler tutorial

Quartz is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time. This tutorial show you how to develop a scheduler job using Quartz 1.6.3. Note This example is a bit outdate, unless you are still using the old Quartz 1.6.3 library, otherwise, …

Read more

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

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

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

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 – What is serialVersionUID

In Java, serialVersionUID is something like version control, assure both serialized and deserialized objects are using the compatible class. For example, if an object saved into a file (Serialization) with serialVersionUID=1L, when we convert the file back to an object (Derialization), we must use the same serialVersionUID=1L, otherwise an InvalidClassException is thrown. Terminal Exception in …

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

Constant value should always come first in comparison

Normal practice Constant value comes second in comparison. private static final String COMPARE_VALUE = "VALUE123"; public boolean compareIt(String input){ if(input.equals(COMPARE_VALUE)){ return true; }else{ return false; } } Problem This is fine to compare a constant value with the above method, however it will potentially causing a NullPointerException, if user pass a “null” value for the …

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