Java try-with-resources example

This article shows you how to use try-with-resources in Java. Table of contents: 1 Java try-with-resources before and after 2. try-with-resources with single resource 3. try-with-resources with multiple resources 3.1 JDBC example. 4. Custom resource with AutoCloseable interface 5. Resource open and closing order 6. Java 9 – final or effectively final variables Download Source …

Read more

How to read file in Java – FileInputStream

In Java, we use FileInputStream to read bytes from a file, such as an image file or binary file. Topics FileInputStream – Read a file FileInputStream – Remaining bytes FileInputStream – Better performance FileInputStream vs BufferedInputStream InputStreamReader – Convert FileInputStream to Reader FileInputStream – Read a Unicode file Note However, all the below examples use …

Read more

The method getRealPath(String) from the type ServletRequest is deprecated

See following example to get the real server file path via servletRequest.getRealPath(“/”). However, warning is prompt and complained that this method is deprecated. import javax.servlet.http.HttpServletRequest; public class DisplayAction { private HttpServletRequest servletRequest; public String execute() { //The method getRealPath(String) from the type ServletRequest is deprecated String filePath = servletRequest.getRealPath("/"); } @Override public void setServletRequest(HttpServletRequest arg0) …

Read more

How to loop ArrayList in Java

No nonsense, four ways to loop ArrayList in Java For loop For loop (Advance) While loop Iterator loop package com.mkyong.core; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListLoopingExample { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Text 1"); list.add("Text 2"); list.add("Text 3"); System.out.println("#1 normal for loop"); for (int i = …

Read more

JAXB hello world example

Jakarta XML Binding (JAXB; formerly Java Architecture for XML Binding) is an XML binding framework to convert Java objects to and from XML. XML Marshalling – Convert Java objects into XML. XML Unmarshalling – Convert XML back into Java Objects. Note This article will focus on Java 11, JAXB 3 and EclipseLink MOXy JAXB RI. …

Read more

Java + MongoDB hello world example

A simple Java + MongoDB hello world example – how to connect, create database, collection and document, save, update, remove, get and display document (data). Tools and technologies used : MongoDB 2.2.3 MongoDB-Java-Driver 2.10.1 JDK 1.6 Maven 3.0.3 Eclipse 4.2 P.S Maven and Eclipse are both optional, just my personal favorite development tool. 1. Create …

Read more

Java – How to convert Char[] to String

In Java, we can use String.valueOf() to convert a char array to a String. JavaSample1.java package com.mkyong.markdown; public class JavaSample1 { public static void main(String[] args) { char[] charArrays = new char[]{‘1’, ‘2’, ‘3’, ‘A’, ‘B’, ‘C’}; String str = new String(charArrays); System.out.println(str); // 123ABC String str2 = String.valueOf(charArrays); System.out.println(str2); // 123ABC } } Output …

Read more

Java – How to convert String to Char Array

In Java, you can use String.toCharArray() to convert a String into a char array. StringToCharArray.java package com.mkyong.utils; public class StringToCharArray { public static void main(String[] args) { String password = "password123"; char[] passwordInCharArray = password.toCharArray(); for (char temp : passwordInCharArray) { System.out.println(temp); } } } Output p a s s w o r d 1 …

Read more

JAX-WS + Java Web Application Integration Example

Often times, JAX-WS always be part of your Java web application. Here we show you how to integrate JAX-WS into Java web application easily. 1. Project Folder First, review this project folder structure. 2. Web Service A super simple web service. Code is self-explanatory. File : HelloWorld.java package com.mkyong.ws; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public …

Read more

How to unzip a WAR file in Java

In J2EE web development, Web Application Archive(WAR) file is just a normal JAR file, which consists all of your web application components like, servlets, Java classes, libraries, resources and etc. Read Wiki for detail. Problem Current web application WAR file is generated via Ant or Maven tool, copy to *nix environment for deployment, but no …

Read more

java.lang.ClassNotFoundException: com.sun.mail.util.MessageRemovedIOException

Problem Use JavaMail API to send Email via GMail smtp server, but hit the following error message : Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MessageRemovedIOException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 1 more P.S The javaee.jar library is included. Solution To solve it, you need to include the …

Read more

How to get MAC address in Java

Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class. In this example, we show you how to get the localhost MAC address in Java. App.java – Get MAC Address via NetworkInterface.getByInetAddress() package com.mkyong; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; public class App{ public static void main(String[] args){ …

Read more

How to get Server IP address in Java

In Java, you can use InetAddress.getLocalHost() to get the Ip Address of the current Server running the Java app. package com.mkyong; import java.net.InetAddress; import java.net.UnknownHostException; public class Test { public static void main(String[] args) { InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); } catch (UnknownHostException e) { e.e.printStackTrace(); …

Read more

How to convert negative number to positive in Java

To convert negative number to positive number (this is called absolute value), uses Math.abs(). This Math.abs() method is work like this “number = (number < 0 ? -number : number);". See a complete example : package com.mkyong; public class app{ public static void main(String[] args) { int total = 1 + 1 + 1 + ...

Read more

Java HttpsURLConnection example

Here’s a simple Java HTTPS client to demonstrate the use of HttpsURLConnection class to send a HTTP GET request yo get the https URL content and certificate detail. P.S You may interest at this example – automate login a website with HttpsURLConnection. HttpsClient.java package com.mkyong.client; import java.net.MalformedURLException; import java.net.URL; import java.security.cert.Certificate; import java.io.*; import javax.net.ssl.HttpsURLConnection; …

Read more

How to validate URL in Java

A short example to show the use of apache.commons.validator.UrlValidator class to validate an URL in Java. import org.apache.commons.validator.UrlValidator; public class ValidateUrlExample{ public static void main(String[] args) { UrlValidator urlValidator = new UrlValidator(); //valid URL if (urlValidator.isValid("https://mkyong.com")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); } //invalid URL if (urlValidator.isValid("http://invalidURL^$&%$&^")) { System.out.println("url is valid"); …

Read more

java.lang.NoClassDefFoundError: org/apache/oro/text/perl/Perl5Util

Problem Validate an URL with Apache common URLValidator to validate an URL, but it hits following error message ? java.lang.NoClassDefFoundError: org/apache/oro/text/perl/Perl5Util at org.apache.commons.validator.UrlValidator.isValid(UrlValidator.java:242) … Caused by: java.lang.ClassNotFoundException: org.apache.oro.text.perl.Perl5Util at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 28 more Solution The URLValidator class is required Jakarta-ORO library, make sure you include the oro-xxx.jar into your project class …

Read more

How to get free disk space in Java

In Java old days, it lacks of method to determine the free disk space on a partition. But this is changed since JDK 1.6 released, a few new methods – getTotalSpace(), getUsableSpace() and getFreeSpace(), are bundled with java.io.File to retrieve the partition or disk space detail. Example package com.mkyong; import java.io.File; public class DiskSpaceDetail { …

Read more

How to make a file read only in Java

A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be writable again. Example package com.mkyong; import java.io.File; import java.io.IOException; public class FileReadAttribute { public static void main(String[] args) throws IOException { File file …

Read more

How to check if a file is hidden in Java

A Java program to demonstrate the use of java.io.File isHidden() to check if a file is hidden. package com.mkyong; import java.io.File; import java.io.IOException; public class FileHidden { public static void main(String[] args) throws IOException { File file = new File("c:/hidden-file.txt"); if(file.isHidden()){ System.out.println("This file is hidden"); }else{ System.out.println("This file is not hidden"); } } } Note …

Read more

Java object sorting example (Comparable and Comparator)

In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value. 1. Sort an Array To sort an Array, use the Arrays.sort(). String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; Arrays.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + …

Read more

How to sort an Array in java

Java example to show the use of Arrays.sort() to sort an Array. The code should be self-explanatory. import java.util.Arrays; import java.util.Collections; public class ArraySorting{ public static void main(String args[]){ String[] unsortStringArray = new String[] {"c", "b", "a", "3", "2", "1"}; int[] unsortIntArray = new int[] {7,5,4,6,1,2,3}; System.out.println("Before sort"); System.out.println("— unsortStringArray —"); for(String temp: unsortStringArray){ System.out.println(temp); …

Read more

How to sort an ArrayList in java

By default, the ArrayList’s elements are display according to the sequence it is put inside. Often times, you may need to sort the ArrayList to make it alphabetically order. In this example, it shows the use of Collections.sort(‘List’) to sort an ArrayList. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortArrayList{ public static void main(String …

Read more

How to sort a Map in Java

Few Java examples to sort a Map by its keys or values. Note If you are using Java 8, refer to this article – How to use Stream APIs to sort a Map 1. Sort by Key 1.1 Uses java.util.TreeMap, it will sort the Map by keys automatically. SortByKeyExample1.java package com.mkyong.test; import java.util.HashMap; import java.util.Map; …

Read more

How to initialize an ArrayList in one line

Here’s a few ways to initialize an java.util.ArrayList, see the following full example: InitArrayList.java package com.mkyong.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class InitArrayList { public static void main(String[] args) { //1. Normal way List<String> list = new ArrayList<String>(); list.add("String A"); list.add("String B"); list.add("String C"); System.out.println("List 1……"); for (String temp : list) { System.out.println(temp); …

Read more

How to check if directory is empty in Java

Here’s an example to check if a directory is empty. Example package com.mkyong.file; import java.io.File; public class CheckEmptyDirectoryExample { public static void main(String[] args) { File file = new File("C:\\folder"); if(file.isDirectory()){ if(file.list().length>0){ System.out.println("Directory is not empty!"); }else{ System.out.println("Directory is empty!"); } }else{ System.out.println("This is not a directory"); } } }

How to delete directory in Java

If we use the NIO Files.delete to delete a non-empty directory in Java, it throws DirectoryNotEmptyException; for legacy IO File.delete to delete a non-empty directory, it returns a false. The standard solution is to loop the directory recursively, and delete all its children’s contents first (sub-files or sub-directories), and delete the parent later. This example …

Read more

How to create directory in Java

In Java, we can use the NIO Files.createDirectory to create a directory or Files.createDirectories to create a directory including all nonexistent parent directories. try { Path path = Paths.get("/home/mkyong/a/b/c/"); //java.nio.file.Files; Files.createDirectories(path); System.out.println("Directory is created!"); } catch (IOException e) { System.err.println("Failed to create directory!" + e.getMessage()); } 1. Create Directory – Java NIO 1.1 We can …

Read more

How to create a temporary file in Java

In Java, we can use the following two Files.createTempFile() methods to create a temporary file in the default temporary-file directory. Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>… attrs) throws IOException Path createTempFile(String prefix, String suffix, FileAttribute<?>… attrs) throws IOException The default temporary file folder is vary on operating system. Windows – %USER%\AppData\Local\Temp Linux – …

Read more

How to delete a temporary file in Java

In Java, we can use the NIO Files.delete() or Files.deleteIfExists() to delete a temporary file, it works the same like delete a regular text file. // create a temporary file Path path = Files.createTempFile(null, ".log"); // delete Files.delete(path); // or if(Files.deleteIfExists(path)){ // success }else{ // file does not exist } 1. Delete Temporary File – …

Read more

How to write to file in Java – BufferedWriter

In Java, we can use BufferedWriter to write content into a file. // jdk 7 try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } Note If possible, uses Files.write instead, one line, simple and nice. List<String> list = Arrays.asList("Line 1", "Line 2"); …

Read more

How to write data to a temporary file in Java

The temporary file is just a regular file created on a predefined directory. In Java, we can use the NIO Files.write() to write data to a temporary file. // create a temporary file Path tempFile = Files.createTempFile(null, null); // Writes a string to the above temporary file Files.write(tempFile, "Hello World\n".getBytes(StandardCharsets.UTF_8)); // Append List<String> content = …

Read more