How to simulate java.lang.OutOfMemoryError in Java
A simple code snippet to simulate the java.lang.OutOfMemoryError: Java heap space
A simple code snippet to simulate the java.lang.OutOfMemoryError: Java heap space
Starts a Java project and hits the below "class not found for com.sun.xml.bind.v2.ContextFactory"? Terminal Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) at jakarta.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:92) at jakarta.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:125) at jakarta.xml.bind.ContextFinder.newInstance(ContextFinder.java:230) … 43 more Solution The com.sun.xml.bind.v2.ContextFactory is under the JAXB APIs; Java 9 deprecated the JAXB, and Java 11 deleted the JAXB completely. To fix …
Migrate a Java project to Java 11 and hits the below "class not found error for JAXBException" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException A short history of JAXB on Java The Jakarta XML Binding (JAXB; formerly Java Architecture for XML Binding) is an XML binding framework to convert Java classes to and from XML. The JAXB is part of …
Using Jersey 3x + Jetty to develop endpoints, but hits the following error during application startup. Terminal Exception in thread "main" java.lang.NoClassDefFoundError: jakarta/servlet/ServletInputStream at org.glassfish.jersey.jetty.JettyHttpContainerProvider.createContainer(JettyHttpContainerProvider.java:43) at org.glassfish.jersey.server.ContainerFactory.createContainer(ContainerFactory.java:58) at org.glassfish.jersey.jetty.JettyHttpContainerFactory.createServer(JettyHttpContainerFactory.java:110) at com.mkyong.MainApp.startServer(MainApp.java:22) at com.mkyong.MainApp.main(MainApp.java:32) Caused by: java.lang.ClassNotFoundException: jakarta.servlet.ServletInputStream at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) … 5 more 1. jakarta/servlet/* and Servlet API 5.0 Since Servlet API …
In Java, if we remove items from a List while iterating it, it will throw java.util.ConcurrentModificationException. This article shows a few ways to solve it. Table of contents 1. java.util.ConcurrentModificationException 2. Java 8 Collection#removeIf 2.1 removeIf examples 2.2 removeIf uses Iterator 3. ListIterator example 4. Filter and Collect example 5. References P.S Tested with Java …
This tutorial shows how to use the Streaming API for XML (StAX) writer to write data to an XML file. Table of contents 1. Write to XML (StAX Writer APIs) 2. Write to XML (StAX Cursor API – XMLStreamWriter) 3. Write to XML (StAX Iterator API – XMLEventWriter) 4. Write and pretty print XML content …
This tutorial shows how to use the Streaming API for XML (StAX) parser to read or parse an XML document. Table of contents 1. What is StAX 1.1 Difference between SAX and StAX? 2. StAX Cursor API and Iterator API 2.1 StAX Cursor API 2.2 StAX Iterator API 2.3 which one? Cursor or Iterator APIs? …
This article shows how to solve the popular JAXB exception Implementation of JAXB-API has not been found on module path or classpath. Table of contents 1. JAXBException: Implementation of JAXB-API has not been found 2. We need a JAXB Implementation 3. JAXB Implementation – Jakarta XML Binding 4. JAXB Implementation – EclipseLink MOXy 4.1 Implementation …
This article shows you how to add, check and remove the byte order mark (BOM) from a UTF-8 file. The UTF-8 representation of the BOM is the byte sequence 0xEF, 0xBB, 0xBF (hexadecimal), at the beginning of the file. 1. Add BOM to a UTF-8 file 2. Check if a file contains UTF-8 BOM 3. …
Java 16 reached General Availability on 16 March 2021, download Java 16 here. Java 16 has 17 JEP items. 1. JEP 338: Vector API (Incubator) 2. JEP 347: Enable C++14 Language Features 3. JEP 357: Migrate from Mercurial to Git 4. JEP 369: Migrate to GitHub 5. JEP 376: ZGC: Concurrent Thread-Stack Processing 6. JEP …
This article shows a few ways to update or increase a value of a key in a HashMap. Table of contents 1. Update the value of a key in HashMap 2. Increase the value of a key in HashMap 3. Java 8 getOrDefault() 4. Java 8 compute and merge 4.1 Java 8 merge example 4.2 …
This article shows a few ways to get keys from value in HashMap. 1. HashMap can contain null for key and value 2. Get all keys from HashMap – keySet() 3. Get keys from value in HashMap 4. Get keys from value in HashMap (Java 8 Stream) 5. HashMap only has one item 6. References …
This article shows how to use Java DOM Parser + XSLT to format or pretty print a XML document. Table of contents 1. An XML file 2. Pretty Print XML via Transformer 3. Pretty Print XML via XSLT 4. Download Source Code 5. References P.S Tested with Java 11 1. An XML file staff-simple.xml <?xml …
With XSLT(Extensible Stylesheet Language Transformations), we can transform XML documents into other formats such as HTML. Table of contents 1. DOM Parser and Transformer 2. DOM example: XML + XSLT = HTML format 3. Download Source Code 4. References P.S Tested with Java 11 1. DOM Parser and Transformer We can use the TransformerFactory to …
In this article, we’ll learn how to read and write Microsoft Word with the help of Apache POI library. Topics Apache POI – HWPF and XWPF Apache POI dependencies Create a word document Working with Paragraphs, Fonts, and Page breaks Document Header and Footer Add Image Create a table Read and parse document, paragraph, and …
Note The BufferedReader reads characters; while the InputStream is a stream of bytes. The BufferedReader can’t read the InputStream directly; So, we need to use an adapter like InputStreamReader to convert bytes to characters format. For example: // BufferedReader -> InputStreamReader -> InputStream BufferedReader br = new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8)); 1. Reads a file …
This article shows different ways to initialize HashMap in Java. Initialize a HashMap (Standard) Collections.singletonMap Java 9 Map.of Java 9 Map.ofEntries Create a function to return a Map Static Initializer Java 8, Stream of SimpleEntry Conclusion After initialized a HashMap, the result is either a mutable map or an immutable map: Mutable map – It …
The Files.find API is available since Java 8. It searches or finds files from a file tree quickly. Topics Files.find() method signature Find files by filename Find files by file size Find files by last modified time In the old days, we always use an error-prone recursive loop to walk a file tree. This Java …
This article shows how to get the file extension of a file in Java. Topics Get file extension normal Get file extension strict Get file extension hardcode Apache Common IO – FilenameUtils Path: /path/foo.txt -> File Extension: txt Path: . -> File Extension: Path: .. -> File Extension: Path: /path/run.exe -> File Extension: exe Path: …
Java 15 reached General Availability on 15 September 2020, download Java 15 here. Java 15 features. 1. JEP 339: Edwards-Curve Digital Signature Algorithm (EdDSA) 2. JEP 360: Sealed Classes (Preview) 3. JEP 371: Hidden Classes 4. JEP 372: Remove the Nashorn JavaScript Engine 5. JEP 373: Reimplement the Legacy DatagramSocket API 6. JEP 374: Disable …
Run a simple java command on Ubuntu and hits the below errors: Terminal $ java -version bash: /usr/bin/java: cannot execute binary file: Exec format error P.S Tested with Java 15 and Ubuntu 20 1. Problem – Download the wrong JDK build The error Exec format error means we download the wrong JDK build for a …
In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName.class .getProtectionDomain() .getCodeSource() .getLocation() .toURI() .getPath(); // non-static String jarPath = getClass() .getProtectionDomain() .getCodeSource() .getLocation() .toURI() .getPath(); Sample output. Terminal /home/mkyong/projects/core-java/java-io/target/java-io.jar 1. Get the path of running JAR 1.1 Create an executable …
This article shows how to convert a File to a Path in Java. java.io.File => java.nio.file.Path // Convert File to Path File file = new File("/home/mkyong/test/file.txt"); Path path = file.toPath(); java.nio.file.Path => java.io.File // Convert Path to File Path path = Paths.get("/home/mkyong/test/file.txt"); File file = path.toFile(); 1. Convert File to Path In Java, we can …
In this tutorial, we will use the Apache Commons Compress library for handling TAR and GZ compression or tar.gz file. Table of Contents: 1. What is tar.gz? 2. Adding Dependencies 3. Creating a tar.gz File in Java 4. Extracting a tar.gz File in Java 5. Adding Files or Directories to an Existing tar.gz File 6. …
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 …
This article shows how to do file transfer from a remote server to the local system and vice versa, using SSH File Transfer Protocol (SFTP) in Java. P.S Tested with JSch 0.1.55 1. JSch Dependency pom.xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> 2. File Transfer – JSch Examples 2.1 In JSch, we can use put and …
This Java example tries to use Jsch to download a file from a remote server to the local system. pom.xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> SFTPFileTransfer.java package com.mkyong.io.howto; import com.jcraft.jsch.*; public class SFTPFileTransfer { private static final String REMOTE_HOST = "1.1.1.1"; private static final String USERNAME = ""; private static final String PASSWORD = ""; …
This Java example tries to use JSch to transfer a file from the local folder to a remote server using public and private keys, instead of a password. pom.xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> SFTPFileTransfer.java package com.mkyong.io.howto; import com.jcraft.jsch.*; public class SFTPFileTransfer { private static final String REMOTE_HOST = "1.1.1.1"; private static final String USERNAME …
In Java, we can use Files.size to get the size of a file; for the directory or folder size, we need to count the size of a directory recursively (sum of the Files.size of all files). This example shows a few common ways to get the size of a directory or folder. FileVisitor (Java 7) …
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 …
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 …
The newline character, also called end of line (EOL), line break, line feed, line separator or carriage return, is a control character to tell the end of a line of text, and the next character should start at a new line. On the Windows system, it is \r\n, on the Linux system, it is \n. …
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)); …
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 …
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 .. …
Argon2 was the winner of the Password Hashing Competition in July 2015, a one-way hashing function that is intentionally resource (CPU, memory, etc) intensive. In Argon2, we can configure the length of the salt, the length of the generated hash, iterations, memory cost, and CPU cost to control the resources that are needed to hash …
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 …
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. …
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 …
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 …