This article shows a few ways to save a byte[] into a file. For JDK 1.7 and above, the NIO Files.write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths.get("/path/file"); Files.write(path, bytes); FileOutputStream is the best alternative. try (FileOutputStream fos = new FileOutputStream("/path/file")) { fos.write(bytes); //fos.close […]

Read more Java – How to save byte[] to a file

In Java, we can use Files.readAllBytes(path) to convert a File object into a byte[]. import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; String filePath = "/path/to/file"; // file to byte[], Path byte[] bytes = Files.readAllBytes(Paths.get(filePath)); // file to byte[], File -> Path File file = new File(filePath); byte[] bytes = Files.readAllBytes(file.toPath()); P.S The NIO Files class is […]

Read more Java – How to convert File to byte[]

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 JDK Timer scheduler 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 JavaMail API – Sending email via Gmail SMTP example

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 – Convert Chinese character to Unicode with native2ascii

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 display chinese character in Eclipse console

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 How to Get Current Timestamps in Java

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 Java MD5 Hashing Example

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 know from where a Class was loaded in Java

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 read an image from file or URL

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 decompress serialized object from a Gzip file

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 What is the different between Set and List

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 How to find files with the file extension in Java

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 Java Properties file examples

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");

Read more How to get a Java Class Object

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 make a Java exe file or executable JAR file

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 Jar manifest error – java.io.IOException: invalid header field

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 How to read and write an image in Java

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 The Java Archive Tool (JAR) Examples

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 How to list out all system drives in your system

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 Java – How to generate serialVersionUID

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 load classes which are not in your classpath

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 add a manifest into a Jar file

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 print out the current project classpath

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 get the standard input in Java