Zip4j – Java Library for ZIP Files (With Examples)

In this tutorial, we show how to use the Zip4j library for handling ZIP files like adding files and directories, updating existing ZIPs, password protection, and encryption. Table of Content: 1. Adding Zip4j Dependency 2. Creating a ZIP File and Adding Files 3. Adding a Directory to ZIP 4. Adding Files to an Existing ZIP …

Read more

Java – Run shell script on a remote server

This article shows how to use JSch library to run or execute a shell script in a remote server via SSH. pom.xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> 1. Run Remote Shell Script This Java example uses JSch to SSH login a remote server (using password), and runs a shell script hello.sh. 1.1 Here is a …

Read more

How to format a double in Java

In Java, we can use String.format or DecimalFormat to format a double, both support Locale based formatting. 1. String.format .2%f For String.format, we can use %f to format a double, review the following Java example to format a double. FormatDouble1.java package com.mkyong.io.utils; import java.util.Locale; public class FormatDouble1 { public static void main(String[] args) { String …

Read more

How to format FileTime in Java

In Java, we can use DateTimeFormatter to convert the FileTime to other custom date formats. public static String formatDateTime(FileTime fileTime) { LocalDateTime localDateTime = fileTime .toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); return localDateTime.format( DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss")); } 1. File Last Modified Time This example displays the last modified time of a file in a custom date format. GetLastModifiedTime.java package …

Read more

Java – Unable to assign group write permission to a file

In Java, we can use the NIO createFile() to assign file permission during file creation. Files.java package java.nio.file; public static Path createFile(Path path, FileAttribute<?>… attrs) throws IOException But, the createFile() fails to assign the group writes file permission to a file on the Unix system? Path path = Paths.get("/home/mkyong/test/runme.sh"); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx"); Files.createFile(path, PosixFilePermissions.asFileAttribute(perms)); …

Read more

How to get file path separator in Java

For file path or directory separator, the Unix system introduced the slash character / as directory separator, and the Microsoft Windows introduced backslash character \ as the directory separator. In a nutshell, this is / on UNIX and \ on Windows. In Java, we can use the following three methods to get the platform-independent file …

Read more

Where is the java.security file?

In Java, we can find the java.security file at the following location: $JAVA_HOME/jre/lib/security/java.security $JAVA_HOME/conf/security For Java 8, and early version, we can find the java.security file at $JAVA_HOME/jre/lib/security/java.security. Terminal $ /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security$ ls -lsah total 12K 4.0K drwxr-xr-x 3 root root 4.0K Mei 12 11:53 . 4.0K drwxr-xr-x 8 root root 4.0K Mei 12 11:53 .. …

Read more

Java – Convert String to Binary

This article shows you five examples to convert a string into a binary string representative or vice verse. Convert String to Binary – Integer.toBinaryString Convert String to Binary – Bit Masking Convert Binary to String – Integer.parseInt Convert Unicode String to Binary. Convert Binary to Unicode String. 1. Convert String to Binary – Integer.toBinaryString The …

Read more

Java – Convert Integer to Binary

In Java, we can use Integer.toBinaryString(int) to convert an Integer to a binary string representative. Integer.java public final class Integer extends Number implements Comparable<Integer>, Constable, ConstantDesc { public static String toBinaryString(int i) { return toUnsignedString0(i, 1); } //… } This article will show you two methods to convert an Integer to a binary string representative. …

Read more

How to reverse a string in Java

In this article, we will show you a few ways to reverse a String in Java. StringBuilder(str).reverse() char[] looping and value swapping. byte looping and value swapping. Apache commons-lang3 For development, always picks the standard StringBuilder(str).reverse() API. For educational purposes, we can study the char[] and byte methods, it involved value swapping and bitwise shifting …

Read more

Java – How to convert a byte to a binary string

In Java, we can use Integer.toBinaryString(int) to convert a byte to a binary string representative. Review the Integer.toBinaryString(int) method signature, it takes an integer as argument and returns a String. Integer.java public final class Integer extends Number implements Comparable<Integer>, Constable, ConstantDesc { public static String toBinaryString(int i) { return toUnsignedString0(i, 1); } //… } If …

Read more

Java – Convert negative binary to Integer

Review the following Java example to convert a negative integer in binary string back to an integer type. String binary = Integer.toBinaryString(-1); // convert -1 to binary // 11111111 11111111 11111111 11111111 (two’s complement) int number = Integer.parseInt(binary, 2); // convert negative binary back to integer System.out.println(number); // output ?? The result is NumberFormatException! Exception …

Read more

Java >> and >>> bitwise shift operators

In programming, bitwise shift operators, >> means arithmetic right shift, >>> means logical right shift, the differences: >>, it preserves the sign (positive or negative numbers) after right shift by n bit, sign extension. >>>, it ignores the sign after right shift by n bit, zero extension. To work with bitwise shift operators >> and …

Read more

How to generate serialVersionUID in Intellij IDEA

In IntelliJ IDEA, we need to enable this auto-generate serialVersionUID option manually. P.S Tested with IntelliJ IDEA 2019.3.4, it should work the same in other versions. Intellij IDEA Settings File -> Settings -> Editor -> Inspections -> Java -> Serialization issues: Find serialization class without serialVersionUID and check it. Back to the editor, clicks on …

Read more

Java – How to generate a random 12 bytes?

In Java, we can use SecureRandom.nextBytes(byte[] bytes) to generate a user-specified number of random bytes. This SecureRandom is a cryptographically secure random number generator (RNG). 1. Random 12 bytes (96 bits) 1.1 Generates a random 12 bytes (96 bits) nonce. HelloCryptoApp.java package com.mkyong.crypto; import java.security.SecureRandom; public class HelloCryptoApp { public static void main(String[] args) { …

Read more

Java 11 – ChaCha20-Poly1305 encryption examples

This article shows you how to encrypt and decrypt a message with the ChaCha20-Poly1305 algorithm, defined in RFC 7539. P.S The ChaCha20-Poly1305 encryption algorithm is available at Java 11. 1. FAQs Some commonly asked questions: 1.1 What is ChaCha20-Poly1305? ChaCha20-Poly1305 means the ChaCha20 (encryption and decryption algorithm) running in AEAD mode with the Poly1305 authenticator. …

Read more

Java – How to join and split byte arrays, byte[]

In this example, we will show you how to join and split byte arrays with ByteBuffer and System.arraycopy. ByteBuffer public static byte[] joinByteArray(byte[] byte1, byte[] byte2) { return ByteBuffer.allocate(byte1.length + byte2.length) .put(byte1) .put(byte2) .array(); } public static void splitByteArray(byte[] input) { ByteBuffer bb = ByteBuffer.wrap(input); byte[] cipher = new byte[8]; byte[] nonce = new byte[4]; …

Read more

Java – Convert byte[] to int and vice versa

In Java, we can use ByteBuffer to convert int to byte[] and vice versa. int to byte[] int num = 1; // int need 4 bytes, default ByteOrder.BIG_ENDIAN byte[] result = ByteBuffer.allocate(4).putInt(number).array(); byte[] to int byte[] byteArray = new byte[] {00, 00, 00, 01}; int num = ByteBuffer.wrap(bytes).getInt(); 1. int to byte[] This Java example …

Read more

Java – What is transient fields?

In Java, transient fields are excluded in the serialization process. In short, when we save an object into a file (serialization), all transient fields are ignored. 1. POJO + transient Review the following Person class; the salary field is transient. public class Person implements Serializable { private static final long serialVersionUID = 1L; private String …

Read more

Java Iterator examples

A few of Java Iterator and ListIterator examples. 1. Iterator 1.1 Get Iterator from a List or Set, and loop over it. JavaIteratorExample1a.java package com.mkyong; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class JavaIteratorExample1a { public static void main(String[] args) { /* Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); Iterator<Integer> iterator = …

Read more

Java List throws UnsupportedOperationException

Typically, we use Arrays.asList or the new Java 9 List.of to create a List. However, both methods return a fixed size or immutable List, it means we can’t modify it, else it throws UnsupportedOperationException. JavaListExample.java package com.mkyong; import java.util.Arrays; import java.util.List; public class JavaListExample { public static void main(String[] args) { // immutable list, cant …

Read more

What is java.util.Arrays$ArrayList?

The java.util.Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array. Arrays.java public static <T> List<T> asList(T… a) { return new ArrayList<>(a); } /** * @serial include */ private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = …

Read more

Java – How to display % in String.Format?

This example shows you how to display a percentage % in String.format. JavaStringFormat1.java package com.mkyong; public class JavaStringFormat1 { public static void main(String[] args) { String result = String.format("%d%", 100); System.out.println(result); } } Output Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ‘%’ at java.base/java.util.Formatter.checkText(Formatter.java:2732) at java.base/java.util.Formatter.parse(Formatter.java:2718) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) Solution To display …

Read more

How to pad a String in Java?

This article shows you how to use the JDK1.5 String.format() and Apache Common Lang to left or right pad a String in Java. 1. String.format By default, the String.format() fills extra with spaces \u0020. Normally, we use replace() to pad with other chars, but it will replace the spaces in between the given string. JavaPadString1.java …

Read more

Java String Format Examples

This article shows you how to format a string in Java, via String.format(). Here is the summary. Conversion Category Description %b, %B general true of false %h, %H general hash code value of the object %s, %S general string %c, %C character unicode character %d integral decimal integer %o integral octal integer, base 8 %x, …

Read more

Java mod examples

Both remainder and modulo are two similar operations; they act the same when the numbers are positive but much differently when the numbers are negative. In Java, we can use Math.floorMod() to describe a modulo (or modulus) operation and % operator for the remainder operation. See the result: | rem & +divisor| rem & -divisor …

Read more

Java Map with Insertion Order

In Java, we can use LinkedHashMap to keep the insertion order. P.S HashMap does not guarantee insertion order. 1. HashMap Generate a HashMap, UUID as key, index 0, 1, 2, 3, 4… as value. JavaHashMap.java package com.mkyong.samples; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.stream.IntStream; public class JavaHashMap { public static void main(String[] args) { …

Read more

Java Trap – Autoboxing and Unboxing

The below program is a typical Java trap, and also a popular Java interview question. It has no compiler error or warning but running very slow. Can you spot the problem? JavaSum.java package com.mkyong; import java.time.Duration; import java.time.Instant; public class JavaSum { public static void main(String[] args) { Instant start = Instant.now(); Long total = …

Read more

Java 8 – Unable to obtain LocalDateTime from TemporalAccessor

An example of converting a String to LocalDateTime, but it prompts the following errors: Java8Example.java package com.mkyong.demo; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class Java8Example { public static void main(String[] args) { String str = "31-Aug-2020"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US); LocalDateTime localDateTime = LocalDateTime.parse(str, dtf); System.out.println(localDateTime); } } Output Exception in thread "main" …

Read more

Java 8 – How to parse date with LocalDateTime

Here are a few Java 8 examples to parse date with LocalDateTime. First, find the DateTimeFormatter pattern that matches the date format, for example: String str = "2020-01-30 12:30:41"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); second, parse it with LocalDateTime.parse DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String str = "2020-01-30 12:30:41"; LocalDateTime localDateTime = LocalDateTime.parse(str, dtf); 1. …

Read more

How to change the JVM default locale?

In Java, we can use Locale.setDefault() to change the JVM default locale. JavaLocaleExample.java package com.mkyong.locale; import java.util.Locale; public class JavaLocaleExample { public static void main(String[] args) { // get jvm default locale Locale defaultLocale = Locale.getDefault(); System.out.println(defaultLocale); // set jvm locale to china Locale.setDefault(Locale.CHINA); // or like this //Locale.setDefault(new Locale("zh", "cn"); Locale chinaLocale = Locale.getDefault(); …

Read more