How to assign file content into a variable in Java

Most people will read the file content and assign to StringBuffer or String line by line. Here’s another trick that may interest you – how to assign whole file content into a variable with one Java’s statement, try it 🙂 Example In this example, you will use DataInputStreamto convert all the content into bytes, and …

Read more

How to traverse a directory structure in Java

In this example, the program will traverse the given directory and print out all the directories and files absolute path and name one by one. Example package com.mkyong.io; import java.io.File; public class DisplayDirectoryAndFile{ public static void main (String args[]) { displayIt(new File("C:\\Downloads")); } public static void displayIt(File node){ System.out.println(node.getAbsoluteFile()); if(node.isDirectory()){ String[] subNote = node.list(); for(String …

Read more

How to open a PDF file in Java

In this article, we show you two ways to open a PDF file with Java. 1. rundll32 – Windows Platform Solution In Windows, you can use “rundll32” command to launch a PDF file, see example : package com.mkyong.jdbc; import java.io.File; //Windows solution to view a PDF file public class WindowsPlatformAppPDF { public static void main(String[] …

Read more

How to clear / delete the content of StringBuffer()

The StringBuffer is always been using for the String concatenation. However this class didn’t provide a method to clear the existing content. Why there are no clear() function? You can use the delete(int start, int end) as dirty trick : sb.delete(0, sb.length()); 1 . Example package com.mkyong.io; public class App{ public static void main (String …

Read more

How to convert HTML to Javascript (.js) in Java

For some security reasons, you may need to convert your HTML file into Javascript (js) file, and display the JS file instead of the HTML file directly. The concept is quite simple – using the document.write HTML <h1>Convert HTML to Javascript file</h1> Javascript (js) document.write(‘<h1>Convert HTML to Javascript file</h1>’); 1. Test.html Create a simple HTML …

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

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

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 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

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 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 get context-param value in java?

The “context-param” tag is define in “web.xml” file and it provides parameters to the entire web application. For example, store administrator’s email address in “context-param” parameter to send errors notification from our web application. web.xml <context-param> <param-name>AdministratorEmail</param-name> <param-value>[email protected]</param-value> </context-param> We can get the above “AdministratorEmail” context-param value with the following java code. String email= getServletContext().getInitParameter("AdministratorEmail"); …

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

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 loop / iterate a List in Java

Here i show you four ways to loop a List in Java. Iterator loop For loop For loop (Adcance) While loop package com.mkyong.core; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class ArrayToList { public static void main(String[] argv) { String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" }; // convert array …

Read more

Bind variables Performance Test in Java

I heard a lot of people talking about “Bind variables” will increase java application performance. Is this really true? i skeptical and make a simple performance test between Bind variables in PreparedStatement class and Non Bind variables in Statement class How do i test it? I will create a simple java class and keep sending …

Read more

How to modify date time (Date Manipulation) – Java

Java Calendar class (java.util.Calendar) is a very useful and handy class in java date time manipulation. here i will demonstrate how to modify date time with calender class. Get current date time with Calendar() DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println("Current Date Time : " + dateFormat.format(cal.getTime())); Calender date time manipulation …

Read more

Java – How to read input from the console

In Java, there are three ways to read input from a console : System.console (JDK 1.6) Scanner (JDK 1.5) BufferedReader + InputStreamReader (Classic) 1. System.console Since JDK 1.6, the developer starts to switch to the more simple and powerful java.io.Console class. JavaConsole.java package com.mkyong.io; import java.io.Console; public class JavaConsole { public static void main(String[] args) …

Read more