How to get the current working directory in Java

In Java, we can use System.getProperty("user.dir") to get the current working directory, the directory from where your program was launched. String dir = System.getProperty("user.dir"); // directory from where the program was launched // e.g /home/mkyong/projects/core-java/java-io System.out.println(dir); One of the good things about this system property user.dir is we can easily override the system property via …

Read more

How to read an object from file in Java (ObjectInputStream)

This example shows how to use ObjectInputStream to read a serialized object from a file in Java, aka Deserialization. public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException { Object result = null; try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { result = ois.readObject(); } return result; } // Convert byte[] to …

Read more

How to write an object to file in Java (ObjectOutputStream)

This example shows how to use ObjectOutputStream to write objects to a file in Java, aka Serialization. public static void writeObjectToFile(Person obj, File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(obj); oos.flush(); } } Note More Java Serialization and Deserialization examples 1. Java object We can …

Read more

How to delete files with certain extension only

In Java, you can implements the FilenameFilter, override the accept(File dir, String name) method, to perform the file filtering function. In this example, we show you how to use FilenameFilter to list out all files that are end with “.txt” extension in folder “c:\\folder“, and then delete it. package com.mkyong.io; import java.io.*; public class FileChecker …

Read more

How to check if a file exists in Java

In Java, we can use Files.exists(path) to test whether a file exists. The path can be a file or a directory. It is better to combine with !Files.isDirectory(path) to ensure the existing file is not a directory. Path path = Paths.get("/home/mkyong/test/test.log"); // file exists and it is not a directory if(Files.exists(path) && !Files.isDirectory(path)) { System.out.println("File …

Read more

Java – How to get current date time

In this tutorial, we will show you how to get the current date time from the new Java 8 java.time.* like Localdate, LocalTime, LocalDateTime, ZonedDateTime, Instant and also the legacy date time APIs like Date and Calendar. Table of contents 1. Get current date time in Java 2. java.time.LocalDate 3. java.time.LocalTime 4. java.time.LocalDateTime 5. java.time.ZonedDateTime …

Read more

How to read XML file in Java – (JDOM Parser)

JDOM is open-source Java-based XML parser framework built on top of DOM and SAX, also a document object model(DOM) in-memory representation of an XML document. JDOM makes navigating XML documents easier by providing more straightforward APIs and a standard Java-based collection interface. If you don’t mind downloading a small library to parse an XML file, …

Read more

How to convert InputStream to File in Java

Below are some Java examples of converting InputStream to a File. Plain Java – FileOutputStream Apache Commons IO – FileUtils.copyInputStreamToFile Java 7 – Files.copy Java 9 – InputStream.transferTo 1. Plain Java – FileOutputStream This example downloads the google.com HTML page and returns it as an InputStream. And we use FileOutputStream to copy the InputStream into …

Read more

SAX Error – Content is not allowed in prolog

We use SAX parser to parse an XML file, and hist the following error message: Terminal org.xml.sax.SAXParseException; systemId: ../src/main/resources/staff.xml; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. In short, invalid text or BOM before the XML declaration or different encoding will cause the SAX Error – Content is not allowed in prolog. 1. …

Read more

Java – How to display all System properties

In Java, you can use System.getProperties() to get all the system properties. Properties properties = System.getProperties(); properties.forEach((k, v) -> System.out.println(k + ":" + v)); // Java 8 1. Example DisplayApp.java package com.mkyong.display; import java.util.Properties; public class DisplayApp { public static void main(String[] args) { Properties properties = System.getProperties(); // Java 8 properties.forEach((k, v) -> System.out.println(k …

Read more

Java – Convert Character to ASCII

In Java, we can cast the char to int to get the ASCII value of the char. char aChar = ‘a’; //int ascii = (int) aChar; // explicitly cast, optional, improves readability int ascii = aChar; // implicit cast, auto cast char to int, System.out.println(ascii); // 97 The explicit cast (int)char is optional, if we …

Read more

How to change Eclipse splash welcome screen image

Eclipse IDE has many customize components, the splash welcome image (purple color loading image) is one of those. I’m very boring to see the purple image loading everyday, a new fresh image will make my development more encouraging 🙂 How to change Eclipse IDE splash image 1) Find “config.ini” file Find the Eclipse’s configuration file …

Read more

How to convert Java source code to HTML page

Java2HTML is a tool to converts Java source code into a colorized and browsable HTML page, and the steps are quite straight forward. Steps to convert it 1) Download Java2HTML – http://www.java2html.com/download.html 2) Unzip it , e.g “D:\Java2HTML” 3) Edit the “j2h.bat” file and modify the CLASSPATH variable. Make sure it point to the correct …

Read more

Java – Create file checksum with SHA and MD5

In this article, we will show you how to use a SHA-256 and MD5 algorithm to generate a checksum for a file. MessageDigest.getInstance(“algorithm”) Apache Commons Codec 1. MessageDigest d:\server.log hello world 1.1 Generate a file checksum with a SHA256 algorithm. FileCheckSumSHA.java package com.mkyong.hashing; import java.io.FileInputStream; import java.io.IOException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class …

Read more

How to convert byte[] to BufferedImage in Java

This article shows how to convert a byte[] to a BufferedImage in Java. InputStream is = new ByteArrayInputStream(bytes); BufferedImage bi = ImageIO.read(is); The idea is puts the byte[] into an ByteArrayInputStream object, and we can use ImageIO.read to convert it to a BufferedImage. 1. Convert byte[] to BufferedImage. The below example shows how to convert …

Read more

How to convert BufferedImage to byte[] in Java

This article shows how to convert a BufferedImage to a byte array or byte[]. BufferedImage bi = ImageIO.read(new File("c:\\image\\mypic.jpg")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "jpg", baos); byte[] bytes = baos.toByteArray(); The idea is uses the ImageIO.write to write the BufferedImage object into a ByteArrayOutputStream object, and we can get the byte[] from the ByteArrayOutputStream. …

Read more

How to Generate an unique ID in Java

Example UUID is the fastest and easiest way to generate unique ID in Java. import java.util.UUID; public class UniqueIDTest { public static void main(String[] args) { UUID uniqueKey = UUID.randomUUID(); System.out.println (uniqueKey); } } Result 0a6a3de7-b974-42d0-af9e-9c23473b09b9

How to get the Tomcat home directory in Java

Q : Is there a function in Java to retrieve the Tomcat (Catalina) home directory? A : Yes, Tomcat home directory or Catalina directory is stored at the Java System Property environment. If the Java web application is deployed into Tomcat web server, we can get the Tomcat directory with the following command System.getProperty("catalina.base");

Java – How to convert Char to String

A Java example to show you how to convert a Char into a String and vise verse. ConvertCharToString.java package com.mkyong.utils; public class ConvertCharToString { public static void main(String[] args) { String website = "https://mkyong.com"; //convert a String into char char charH = website.charAt(0); //h char charP = website.charAt(3);//p char charM = website.charAt(11);//m System.out.println(charH); System.out.println(charP); System.out.println(charM); …

Read more

How to detect OS in Java

This article shows a handy Java class that uses System.getProperty("os.name") to detect which type of operating system (OS) you are using now. 1. Detect OS (Original Version) This code can detect Windows, Mac, Unix, and Solaris. OSValidator.java package com.mkyong.system; public class OSValidator { private static String OS = System.getProperty("os.name").toLowerCase(); public static void main(String[] args) { …

Read more

How to read a UTF-8 file in Java

In Java, the InputStreamReader accepts a charset to decode the byte streams into character streams. We can pass a StandardCharsets.UTF_8 into the InputStreamReader constructor to read data from a UTF-8 file. import java.nio.charset.StandardCharsets; //… try (FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(isr) ) { String str; …

Read more

How to write a UTF-8 file in Java

In Java, the OutputStreamWriter accepts a charset to encode the character streams into byte streams. We can pass a StandardCharsets.UTF_8 into the OutputStreamWriter constructor to write data to a UTF-8 file. try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); BufferedWriter writer = new BufferedWriter(osw)) { writer.append(line); } In Java 7+, many …

Read more

How to suppress unchecked warnings – Java

The ‘unchecked warnings’ is quite popular warning message in Java. However, if you insist this is an invalid warning, and there are no ways to solve it without compromising the existing program functionality. You may just use @SuppressWarnings(“unchecked”) to suppress unchecked warnings in Java. 1. In Class If applied to class level, all the methods …

Read more

How to encode a URL string or form parameter in java

This is always advisable to encode URL or form parameters; plain form parameter is vulnerable to cross site attack, SQL injection and may direct our web application into some unpredicted output. A URL String or form parameters can be encoded using the URLEncoder class – static encode (String s, String enc) method. For example, when …

Read more

How to escape special characters in java?

In Java, we can use Apache commons-text to escape the special characters in HTML entities. Special characters as follow: < > ” & pom.xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency> EscapeSpecialChar.java package com.mkyong.html; import org.apache.commons.text.StringEscapeUtils; // @deprecated as of 3.6, use commons-text StringEscapeUtils instead //import org.apache.commons.lang3.StringEscapeUtils; public class EscapeSpecialChar { public static void main(String[] args) { …

Read more

How to run a java program in backgroud (unix / Linux)

Oftentimes, we use SSH to remote access into the server to run a Java program. The problem is, we can’t type anything After the Java program is executed like this : $ java -jar example.jar In addition, when the remote access session is expired or terminated, the executed Java program will be killed. Solution To …

Read more

How to convert String to byte[] in Java?

In Java, we can use str.getBytes(StandardCharsets.UTF_8) to convert a String into a byte[]. String str = "This is a String"; // default charset, a bit dangerous byte[] output1 = str.getBytes(); // in old days, before java 1.7 byte[] output2 = str.getBytes(Charset.forName("UTF-8")); // the best , java 1.7+ , new class StandardCharsets byte[] output3 = str.getBytes(StandardCharsets.UTF_8); …

Read more

How to convert byte[] array to String in Java

In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String. // string to byte[] byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8); // byte[] to string String s = new String(bytes, StandardCharsets.UTF_8); Table of contents 1. byte[] in text and binary data 2. Convert byte[] to String (text data) 3. Convert byte[] to String …

Read more

JCE Encryption – Data Encryption Standard (DES) Tutorial

In this article, we show you how to use Java Cryptography Extension (JCE) to encrypt or decrypt a text via Data Encryption Standard (DES) mechanism. 1. DES Key Create a DES Key. KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); SecretKey myDesKey = keygenerator.generateKey(); 2. Cipher Info Create a Cipher instance from Cipher class, specify the following information and …

Read more

Java’s silent killer – Integer Overflow, Careful !

Believe it or not, Java contains Integer buffer overflow as well. I’m not sure is this the correct word to describe it or not, may be you can suggest some 🙂 OK, please take a look at below program, this program print the number of microseconds in a day. public class JavaLongOverflow { public static …

Read more

How to calculate monetary values in Java

There are many monetary values calculation in the financial or e-commerce application, and there is one question that arises for this – Should we use double or float data type to represent the monetary values? Answer: Always uses java.math.BigDecimal to represent the monetary values. 1. Double or Float? Here is an example of using double …

Read more

How to get time in milliseconds in Java

In Java, you can use following methods to get time in milliseconds Date class – getTime() method Calendar class – getTimeInMillis() method TimeMilisecond.java package com.mkyong.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class TimeMilisecond { public static void main(String[] argv) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String dateInString = "22-01-2015 …

Read more

How to calculate elapsed / execute time in Java

In Java, you can use the following ways to measure elapsed time in Java. 1. System.nanoTime() This is the recommended solution to measure elapsed time in Java. ExecutionTime1.java package com.mkyong.time; import java.util.concurrent.TimeUnit; public class ExecutionTime1 { public static void main(String[] args) throws InterruptedException { //start long lStartTime = System.nanoTime(); //task calculation(); //end long lEndTime = …

Read more