How to escape HTML in Java

In Java, we can use Apache commons-text, StringEscapeUtils.escapeHtml4(str) to escape HTML characters. pom.xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency> JavaEscapeHtmlExample.java package com.mkyong.html; // make sure import the correct commons-text package import org.apache.commons.text.StringEscapeUtils; // @deprecated as of 3.6, use commons-text StringEscapeUtils instead //import org.apache.commons.lang3.StringEscapeUtils; public class JavaEscapeHtmlExample { public static void main(String[] args) { String html = …

Read more

Java – How to get all links from a web page?

A jsoup HTML parser example to show you how to parse and get all HTML hyperlinks from a web page: pom.xml <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency> JsoupFindLinkSample.java package com.mkyong; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class JsoupFindLinkSample { public static void main(String[] args) throws IOException { …

Read more

Java – Pretty Print HTML

In Java, we can use jsoup, a Java HTML parser, to parse a HTML code and pretty print it. pom.xml <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency> JavaPrettyPrintHTML.java package com.mkyong; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class JavaPrettyPrintHTML { public static void main(String[] args) { String html = "<html><body><h1>hello world</h1></body></html>"; System.out.println(html); // original Document doc = Jsoup.parse(html); // …

Read more

Java – How to read input from console using Scanner

This example shows you how to read input from the console using the standard java.util.Scanner class. JavaScanner.java package com.mkyong.io; import java.util.Scanner; public class JavaScanner { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); System.out.print("Please enter your …

Read more

Java – How to read input from System.console()

In Java, we can use System.console() to read input from the console. JavaSample.java package com.mkyong.io; import java.io.Console; public class JavaSample { public static void main(String[] args) { // jdk 1.6 Console console = System.console(); System.out.print("Enter your name: "); String name = console.readLine(); System.out.println("Name is: " + name); System.out.print("Enter your password: "); // Reads a password …

Read more

Java – Server returned HTTP response code: 403 for URL

A simple Java program tries to download something from the internet: try (InputStream is = new URL(url).openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { while ((line = br.readLine()) != null) { result.append(line); } } But, some web servers return the following HTTP 403 errors? Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 …

Read more

Java – How to print name 1000 times without looping?

Here’s a Java example to print a name 1000 times without looping or recursion, instead, use String concatenation and simple math. Just for fun. JavaNoLoop.java package com.mkyong.samples; public class JavaNoLoop { public static void main(String[] args) { String s1 = "Mkyong\n"; String s3 = s1 + s1 + s1; String s10 = s3 + s3 …

Read more

Java – How to enable the preview language features?

This article shows you how to use –enable-preview to enable the preview language features in Java 12, 13 and above. Note Read this JEP 12: Preview Language and VM Features P.S All preview features are disabled by default. On JDK 12: # compile javac Example.java // Do not enable any preview features javac –release 12 …

Read more

Java Ternary Operator examples

This example shows you how to write Java ternary operator. Here’s the syntax condition ? get_this_if_true : get_this_if_false Java ternary operator syntax (n > 18) ? true : false; (n == true) ? 1 : 0; (n == null) ? n.getValue() : 0; 1. Java ternary operator 1.1 Java example without ternary operator. JavaExample1.java package …

Read more

Java – How to search a string in a List?

In Java, we can combine a normal loop and .contains(), .startsWith() or .matches() to search for a string in ArrayList. JavaExample1.java package com.mkyong.test; import java.util.ArrayList; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Kotlin"); list.add("Clojure"); list.add("Groovy"); list.add("Scala"); List<String> result = new ArrayList<>(); for (String s …

Read more

Java 11 HttpClient Examples

This article shows you how to use the new Java 11 HttpClient APIs to send HTTP GET/POST requests, and some frequent used examples. HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .followRedirects(HttpClient.Redirect.NORMAL) .connectTimeout(Duration.ofSeconds(20)) .proxy(ProxySelector.of(new InetSocketAddress("proxy.yourcompany.com", 80))) .authenticator(Authenticator.getDefault()) .build(); 1. Synchronous Example This example sends a GET request to https://httpbin.org/get, and print out the response header, status code, and …

Read more

OkHttp – How to send HTTP requests

This article shows you how to use the OkHttp library to send an HTTP GET/POST requests and some frequent used examples. P.S Tested with OkHttp 4.2.2 pom.xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.2</version> </dependency> 1. Synchronous Get Request OkHttpExample1.java package com.mkyong.http; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample1 { // only …

Read more

Apache HttpClient Basic Authentication Examples

This article shows you how to use Apache HttpClient to perform an HTTP basic authentication. P.S Tested with HttpClient 4.5.10 pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> Start a simple Spring Security WebApp providing HTTP basic authentication, and test it with the HttpClient 1. Basic Authentication The key is to configure CredentialsProvider and pass it to …

Read more

Java 13 – Switch Expressions

In Java 13, the JEP 354: Switch Expressions extends the previous Java 12 Switch Expressions by adding a new yield keyword to return a value from the switch expression. P.S Switch expressions are a preview feature and are disabled by default. Note This is a standard feature in Java 14. 1. No more value breaks! …

Read more

What is new in Java 13

Java 13 reached General Availability on 17 September 2019, download Java 13 here or this openJDK archived. Java 13 features. 1. JEP 350 Dynamic CDS Archives 2. JEP 351 ZGC: Uncommit Unused Memory 3. JEP-353 Reimplement the Legacy Socket API 4. JEP-354 Switch Expressions (Preview) 5. JEP-355 Text Blocks (Preview) Java 13 developer features. Switch …

Read more

Java 12 – Switch Expressions

Java 12, JEP 325: Switch Expressions enhanced the traditional switch statement to support the following new features: Multiple case labels Switch expression returning value via break (replaced with yield in Java 13 switch expressions) Switch expression returning value via label rules (arrow) P.S Switch expressions are a preview feature and are disabled by default. A …

Read more

Java – Get the last element of a list

In Java, index starts at 0, we can get the last index of a list via this formula: list.size() – 1 JavaExample1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); System.out.println(list.get(list.size() – 1)); System.out.println(list.get(list.size() – 2)); System.out.println(list.get(list.size() – 3)); …

Read more

Java – How to get keys and values from Map

In Java, we can get the keys and values via map.entrySet() Map<String, String> map = new HashMap<>(); // Get keys and values for (Map.Entry<String, String> entry : map.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); System.out.println("Key: " + k + ", Value: " + v); } // Java 8 map.forEach((k, v) -> { …

Read more

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long

Below example, the jdbcTemplate.queryForList returns an object of Integer and we try to convert it into a Long directly: public List<Customer> findAll() { String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); for (Map row : rows) { Customer obj = new Customer(); obj.setID(((Long) row.get("ID"))); // the …

Read more

Java – How to lock a file before writing

In Java, we can combine RandomAccessFile and FileChannel to lock a file before writing. LockFileAndWrite.java package com.mkyong; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileLock; import java.util.concurrent.TimeUnit; public class LockFileAndWrite { public static void main(String[] args) { writeFileWithLock(new File("D:\\server.log"), "mkyong"); } public static void writeFileWithLock(File file, String content) { // auto close and release the …

Read more

Java – How to read last few lines of a File

In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File. pom.xml <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> 1. Test Data A server log file sample d:\\server.log a b c d 1 2 3 4 5 2. Read Last Line 2.1 Read the last 3 lines of a …

Read more

Java Regular Expression Examples

Java 8 stream and regular expression examples. Note Learn the basic regular expression at Wikipedia 1. String.matches(regex) 1.1 This example, check if the string is a number. JavaRegEx1.java package com.mkyong.regex; import java.util.Arrays; import java.util.List; public class JavaRegEx1 { public static void main(String[] args) { List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211"); for (String number …

Read more

Java 8 Stream – Convert List<List<String>> to List<String>

As title, we can use flatMap to convert it. Java9Example1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class Java9Example1 { public static void main(String[] args) { List<String> numbers = Arrays.asList("1", "2", "A", "B", "C1D2E3"); List<List<String>> collect = numbers.stream() .map(x -> new Scanner(x).findAll("\\D+") .map(m -> m.group()) .collect(Collectors.toList()) ) .collect(Collectors.toList()); collect.forEach(x -> System.out.println(x)); …

Read more

How to loop an enum in Java

Call the .values() method of the enum class to return an array, and loop it with the for loop: for (EnumClass obj : EnumClass.values()) { System.out.println(obj); } For Java 8, convert an enum into a stream and loop it: Stream.of(EnumClass.values()).forEach(System.out::println); 1. For Loop Enum 1.1 An enum to contain a list of the popular JVM …

Read more

Java – Convert Integer to Long

In Java, we can use Long.valueOf() to convert an Integer to a Long TestInteger.java package com.mkyong.example; public class TestInteger { public static void main(String[] args) { Integer num = 1; System.out.println(num); // 1 Long numInLong = Long.valueOf(num); System.out.println(numInLong); // 1 } } References Long.valueOf JavaDocs)

Java – How to change date format in a String

If Java 8, DateTimeFormatter, else SimpleDateFormat to change the date format in a String. 1. DateTimeFormatter (Java 8) Convert the String to LocalDateTime and change the date format with DateTimeFormatter DateFormatExample1.java package com.mkyong; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateFormatExample1 { // date format 1 private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); // date …

Read more

Java – Add new line in String

Different operating system has a different new line or line separator string: UNIX, Linux or Mac OSX = \n Windows = \r\n NewLineExample.java package com.mkyong; public class NewLineExample { public static void main(String[] args) { String original = "Hello World Java"; System.out.println(original); // add new line String originalNewLine = "Hello\nWorld\nJava"; System.out.println(originalNewLine); } } Output Hello …

Read more

Java 8 – Should we close the Stream after use?

Only Streams whose source are an IO channel like Files.lines(Path, Charset) need to be closed. Read this Stream JavaDocs Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by …

Read more

Java – Convert File to String

In Java, we have many ways to convert a File to a String. A text file for testing later. c:\\projects\\app.log A B C D E 1. Java 11 – Files.readString A new method Files.readString is added in java.nio.file.Files, it makes reading a string from File much easier. FileToString1.java package com.mkyong; import java.io.IOException; import java.nio.file.Files; import …

Read more

Java – How to save a String to a File

In Java, there are many ways to write a String to a File. 1. Java 11 – Files.writeString Finally, a new method added in java.nio to save a String into a File easily. StringToFileJava11.java package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class StringToFileJava11 { public static void main(String[] args) …

Read more

FastJson – Convert Java objects to / from JSON

FastJson provides easily APIs to convert Java objects to / from JSON JSON.toJSONString – Java objects to JSON JSON.parseObject – JSON to Java objects JSON.parseArray – JSON array to List of Java objects Note You may have interest to read this How to parse JSON with Jackson Overall, the FastJson is really simple and easy …

Read more

Java password generator example

Here’s the Java password generator to generate a secure password that consists of two lowercase chars, two uppercase chars, two digits, two special chars, and pad the rest with random chars until it reaches the length of 20 characters. Secure password requirements: Password must contain at least two digits [0-9]. Password must contain at least …

Read more

Java – How to generate a random String

Few Java examples to show you how to generate a random alphanumeric String, with a fixed length. 1. Random [a-ZA-Z0-9] 1.1 Generate a random alphanumeric String [a-ZA-Z0-9], with a length of 8. RandomExample.java package com.mkyong; import java.security.SecureRandom; public class RandomExample { private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase(); …

Read more

Java – Convert String to double

In Java, we can use Double.parseDouble() to convert a String to double 1. Double.parseDouble() Example to convert a String 3.142 to an primitive double. String str = "3.142"; double pi = Double.parseDouble(str); System.out.println(pi); Output 3.142 2. Double.valueOf() Example to convert a String 3.142 to an Double object. String str = "3.142"; Double pi = Double.valueOf(str); …

Read more

Java – Convert Array to ArrayList

In Java, we can use new ArrayList(Arrays.asList(array)) to convert an Array into an ArrayList ArrayExample1.java package com.mkyong; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayExample1 { public static void main(String[] args) { String[] str = {"A", "B", "C"}; List<String> list = new ArrayList<>(Arrays.asList(str)); list.add("D"); list.forEach(x -> System.out.println(x)); } } Output A B C D …

Read more

JSON.simple – How to parse JSON

In this tutorial, we will show you how to parse JSON with JSON.simple Note You may have interest to read – How to parse JSON with Jackson or Gson JSON.simple short history This project was formerly JSON.simple 1.x from a Google code project by Yidong, now maintaining by Clifton Labs, read this JSON.simple history P.S …

Read more

Java – How to check if a String is numeric

Few Java examples to show you how to check if a String is numeric. 1. Character.isDigit() Convert a String into a char array and check it with Character.isDigit() NumericExample.java package com.mkyong; public class NumericExample { public static void main(String[] args) { System.out.println(isNumeric("")); // false System.out.println(isNumeric(" ")); // false System.out.println(isNumeric(null)); // false System.out.println(isNumeric("1,200")); // false System.out.println(isNumeric("1")); …

Read more

Java – Check if a String is empty or null

In Java, we can use (str != null && !str.isEmpty()) to make sure the String is not empty or null. StringNotEmpty.java package com.mkyong; public class StringNotEmpty { public static void main(String[] args) { System.out.println(notEmpty("")); // false System.out.println(notEmpty(null)); // false System.out.println(notEmpty("hello")); // true System.out.println(notEmpty(" ")); // true, a space… } private static boolean notEmpty(String str) { …

Read more