الخميس، 17 يونيو 2021

Java 8 Stream Group By Count Example

1. Introduction


We will learn how to get the count using the stream group by count technique in this lesson. This is a very helpful way to do aggregated operations with the Java 8 stream grouping API.

Collectors.groupingBy() and Collectors.counting() are used to accomplish the group by count operation.

Let's look at some examples of stream grouping by count.

Java 8 Stream Group By Count Example

الأربعاء، 16 يونيو 2021

Windows Grep Equivalent – findstr Examples for Grep Command

1. Overview

In this tutorial, We'll learn how to use the unix grep command in windows to search the files efficiently and what is the windows grep equivalent tool or command.

When you are using windows machine, many times you might have encountered the situations to search a piece of text in the windows machine.

After doing research, we found that there is a tool called findstr for windows operating system which matches to the grep command.

Let us explore the different type of search using findstr command.

Grep for Windows – findstr Examples for Grep Command


2. By Filtering the Results


First, use the ls command and filter the results using grep command.

// example of unix grep command to filter
ls -l | grep javaprogramto

// windows equivalent command
dir | findstr javaprogramto

We can pass the multiple search patterns to the grep and findstr command.

unix grep: Use -E flag with grep command to pass multiple patterns and delimited by | pipe symbol. This pattern should be enclosed in double quotes.
windows findstr: Just need to pass the space separator to findstr command and keep the patterns in double quotes.

// example of unix grep command to filter
ls -l | grep -iE "javaprogramto|kotlin"

// windows equivalent command
dir | findstr "javaprogramto kotlin"

3. By Searching the Files


Let see now how to find the matches the in file for a specific pattern.

Below example is to find the match and second one is for get the matches count.

#Example 1
#Linux - find the matches
$ grep javaprogramto input.txt

#Windows - find the matches
c:\> findstr javaprogramto input.txt

#Example 2
#Linux - count the matches
$ grep -c javaprogramto input.txt

#Windows - count the matches
c:\> findstr -N javaprogramto input.txt


unix: -c flag works with grep command to get the count for the matched records
windows: -N flag for findstr

4. By Searching List Of Files


Next, search for a files names which has the given pattern in the given folder.

#Example 1
#Linux - search in folders
$ grep javaprogramto  -lr /path/folder

#Windows - search in folder files
c:\> findstr /M javaprogramto c:\folder\*


5. Help Command


We can get the help command for grep and findstr.

#Example to get help from provider
$ grep --help 
$ man grep 

#Windows
c:\> findstr -?

6. Conclusion


In this article, We've seen how to search files in windows just like unix grep command and shown the examples.


الثلاثاء، 15 يونيو 2021

Spring Boot - How to Change Default Port in Spring Application?

1. Introduction

In this tutorial, You'll learn how to change the default port to new custom port in Spring Boot application.

Spring Boot by default does many auto configurations and provides the ways to customize as per the need.

The most common use case is changing the port of application to the new one. Because by default embedded tomcat is configured with 8080 port. If you already another service that is running on the same port then you can not start a new service on that port. So, you must have to run the application on a different port. 

Changing the port can be done in many possible ways.

Let us see one be one with practical example programs.

الاثنين، 14 يونيو 2021

Kotlin - Convert Map to List Examples

1. Overview

In this tutorial, We will learn how to convert the Map to List in kotlin programming. Map implementations such as HashMap or TreeMap can be converted into an ArrayList or List object.

Let us explore the different ways to do conversion from map to get the list of keys and values.

Kotlin - Convert Map to List Examples



2. Converting HashMap to List in Kotlin Using ArrayList Constructor


This approach is the simple one and easy. First create the HashMap object with HashMap() constructor
Next, adding few key value pairs to the map. Use map.keys and map.values to get the all keys and values.
pass these values to ArrayList constructor to convert the map to list.

These properties will be invoking the below functions internally when you are using java.util.HashMap.

map.keys --> map.keySet()
map.values --> map.values()

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var map = HashMap<Int, String>();

    map.put(10, "Ten")
    map.put(20, "Twenty")
    map.put(30, "Thirty")
    map.put(40, "Fourty")
    map.put(50, "Fifty")

    var keysList = ArrayList(map.keys);
    var valuesList = ArrayList(map.values);

    println("Keys list : $keysList")
    println("Values list : $valuesList")

}

Output:
Keys list : [50, 20, 40, 10, 30]
Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

3. Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor


From the above program, the output is not in the order what is inserted into the map. To preserve the insertion order then need to use LinkedHashMap class instead of HashMap.

Look at the below program and observer the output order.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    // to holds the insertion order
    var map = LinkedHashMap<Int, String>();

    map.put(10, "Ten")
    map.put(20, "Twenty")
    map.put(30, "Thirty")
    map.put(40, "Fourty")
    map.put(50, "Fifty")

    // gets the keys and values as per the insertion
    var keysList = ArrayList(map.keys);
    var valuesList = ArrayList(map.values);

    // prints
    println("Keys list : $keysList")
    println("Values list : $valuesList")
}
Output:
Keys list : [10, 20, 30, 40, 50]
Values list : [Ten, Twenty, Thirty, Fourty, Fifty]


4. Kotlin Map to List using toList() method


Use toList() method on map object or keys, values properties.

package com.javaprogramto.kotlin.collections.map.list
import java.util.HashMap

fun main(array: Array<String>) {

    var map = HashMap<Int, String>();

    map[10] = "Ten"
    map[20] = "Twenty"
    map[30] = "Thirty"
    map[40] = "Fourty"
    map[50] = "Fifty"

    // example 1 using toList() method
    var keysList = map.keys.toList();
    var valuesList = map.values.toList();
    println("using toList()")
    println("Keys list : $keysList")
    println("Values list : $valuesList")

    // example 2 using toList() method

    var mutableMap: MutableMap<Int, String> = HashMap()
    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var entries = mutableMap.toList().map { "(${it.first}, ${it.second})"}
    println("\nusing toList() on mutable map")
    entries.forEach{print("$it ")}
}

Output:

using toList()
Keys list : [50, 20, 40, 10, 30]
Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

using toList() on mutable map
(50, Fifty) (20, Twenty) (40, Fourty) (10, Ten) (30, Thirty) 

5. Kotlin Map to List using entries properties


map.entries properties will returns the key-value pairs. Use map() method  on the entries object.  We can use the any pattern in between the key and value.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var mutableMap: MutableMap<Int, String> = HashMap()

    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var list : List<String> = mutableMap.entries.map { ("${it.key} -->  ${it.value}") }

    list.forEach{println(it)}
}

Output:

50 -->  Fifty
20 -->  Twenty
40 -->  Fourty
10 -->  Ten
30 -->  Thirty

6. Kotlin Map to List using keys and values


Use keys and values properties of map object to call map() method.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var mutableMap: MutableMap<Int, String> = HashMap()

    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var keysList : List<String> = mutableMap.keys.map { ("${it} ") }
    var valuesList : List<String> = mutableMap.values.map { ("${it} ") }

    println("---- keys list ------")
    keysList.forEach{println(it)}

    println("----- values list ------")
    valuesList.forEach{println(it)}
}

Output:

---- keys list ------
50 
20 
40 
10 
30 
----- values list ------
Fifty 
Twenty 
Fourty 
Ten 
Thirty 

7. Conclusion


in this article, We have seen how to convert Map to List in Kotlin programming and examples on different approaches.



الأحد، 13 يونيو 2021

Java 8 IntStream With Working Examples

1. Overview

In this tutorial, We'll learn how to use the IntStream in java 8 and it uses with example programs.

For int primitives, the Java IntStream class is a specialization of the Stream interface. It's a stream of primitive int-valued items that can be used in both sequential and parallel aggregate operations.

AutoCloseable and BaseStream interfaces are implemented by IntStream, which is part of the java.util.stream package.

We will learn the following topics in this course.

  • IntStream Creation
  • ForEach loop
  • IntStream ranges
  • IntStream min and max
  • IntStream find
  • IntStrem map
  • IntStream filter
  • IntStream distinct
  • IntStream to Array
  • IntStream to List
Java 8 IntStream With Working Examples


2. Creating IntStream


An IntStream can be generated in a variety of ways, but it cannot be created using a new keyword.

The IntStream objects are created using the methods listed below.

  • IntStream.of()
  • IntStream.range()
  • IntStream.rangeclosed()
  • IntStream.generate()
  • IntStream.iterate()

Let us explore the ways to use these methods with example programs. to create an instance for IntStream with primitive int values.

2.1 IntStream.of()


This function returns a sequentially ordered stream with the provided values as its elements.

It is available in two forms: single element stream and multiple values stream.

IntStream of(int t) – Returns a stream consisting of a single supplied element.
IntStream of(int... values) – Returns a stream with all the components supplied.
package com.javaprogramto.java8.intstream;

import java.util.stream.IntStream;

public class IntStreamOf {

	public static void main(String[] args) {

		IntStream singleValue = IntStream.of(10);

		IntStream multipleValeus = IntStream.of(1, 5, 10, 20, 30);

	}

}
 

2.2 IntStream.range()


range() is used to generate the numbers in the order with incremental by one.

static IntStream range(int startInclusive, int endExclusive) -- here the end range is exclusive.

IntStream range10to30 = IntStream.range(10, 20);
 

2.3 IntStream.rangeclosed()


rangeClosed() is also used to generate the numbers in the order with incremental by one but it includes the end index of this method.

static IntStream rangeClosed(int startInclusive, int endInclusive)
IntStream range10to15closed = IntStream.range(10, 15);
 

2.4 IntStream.generate()


Use the generate() method if you wish to generate random numbers with custom logic.
IntStream random = IntStream.generate( () -> { return (int) Math.random() * 5000;});
 

2.5 IntStream.iterate()


The iterate() method is identical to the generate() method, except instead of random values, it uses incremental or decrement custom logic for large values.

Due to the fact that the iterate() method generates an infinite stream of integers, you must use the limit() function to get the first n numbers.
IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
 

3. IntStream forEach()


Typically we can use the traditional for loop for certain range. However, the same thing may be accomplished by using the IntStream.forEach() function instead.
package com.javaprogramto.java8.intstream;

import java.util.stream.IntStream;

public class IntStreamOf {

	public static void main(String[] args) {
		
		System.out.println("for loop");
		for(int i = 1000; i < 20000 ; i = i + 4000) {
			print(i);
		}
		
		System.out.println("intstream foreach loop");
		IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
		
		iterate.forEach(n -> print(n));
		
		
	}
	
	private static void print(int n) {
		System.out.println(n);
	}

}

 

4. IntStream ranges 


Two methods are offered by the IntStream API to work with numbers generated in a defined range.

range(start, endExclusive): excludes the end index from the output range.

rangeClosed(start, endInclusive): this method includes the end index from the output range.

The below program output gives you clear understanding between range() and rangeClosed() methods.
		IntStream range10to15range = IntStream.range(10, 15);
		IntStream range10to15closed = IntStream.rangeClosed(10, 15);
		
		System.out.println("range(10, 15) : "+Arrays.toString(range10to15range.toArray()));
		System.out.println("rangeClosed(10, 15) : "+Arrays.toString(range10to15closed.toArray()));
 
Output:
range(10, 15) : [10, 11, 12, 13, 14]
rangeClosed(10, 15) : [10, 11, 12, 13, 14, 15]
 

5. IntStream min and max


IntStream has utility methods for determining the minimum and maximum values from a series of numbers or random numbers.

Use min() method to retrieve the lowest value from int stream.
Use max() method to retrieve the highest value from int stream.
System.out.println("range(10, 15) min value : "+IntStream.range(10, 15).min().getAsInt());
System.out.println("range(10, 15) max value : "+IntStream.range(10, 15).max().getAsInt());
 
Output:
range(10, 15) min value : 10
range(10, 15) max value : 14
 

6. IntStream find value


Use findFirst() or findAny() methods on the InstStream object to get the first or any value.


By default, IntStream is created as sequential stream unless call the parallel() on the IntStream.

For sequential streams, the findFirst() and findAny() methods return the same result. If the stream is parallel, however, the findAny() method gives a random value.
System.out.println("findFirst value : "+IntStream.iterate(10, i -> i + 2).limit(100).findFirst().getAsInt());
System.out.println("findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).findAny().getAsInt());

System.out.println("parallel findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).parallel().findAny().getAsInt());
 
Output:
findFirst value : 10
findAny value : 10
parallel findAny value : 160
 

7. IntStream map() or flatMap()


We can transform the IntStream into the new form using map() method but flatMap() method does the flatten the IntStreams into primitives.

Usage of map() and flatMap() does not give much difference with IntStream usage.
IntStream mapInput = IntStream.iterate(10, i -> i + 1).limit(10);

System.out.println("map input stream : "+Arrays.toString(mapInput.toArray()));

IntStream mapOutput = mapInput.map( i -> i * 2);

System.out.println("map Output stream : "+Arrays.toString(mapOutput.toArray()));


IntStream input1 = IntStream.iterate(10, i -> i + 1).limit(10);

System.out.println("flat map : "+Arrays.toString(input1.flatMap( i -> IntStream.of(i)).toArray()));
 

Output:
map input stream : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
map Output stream : [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
flat map : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

 

8. IntStream filter


Use filter() method to filter the integer values based on the given IntPredicate condition.

After applying the filter() method then next you can call forEach() or collect() method to convert it into List or Set.
IntStream stream = IntStream.range(100, 200);

// filter by number divisible by 5 and 7
System.out.println("numbers divisible by 5 and 7 are : ");
stream.filter(i -> (i % 5 == 0 && i % 7 == 0)).forEach(System.out::println);

IntStream stream2 = IntStream.range(100, 200);

List<Integer> primes = stream2.filter(IntStreamOf::checkPrime).boxed().collect(Collectors.toList());

System.out.println("Prime numbers (100, 200) are "+primes);
 
Output:
numbers divisible by 5 and 7 are : 
105
140
175
Prime numbers (100, 200) are [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]

 

9. IntStream distinct()


Use distinct() method to remove the duplicate values from IntStream.
Arrays.toString(IntStream.of(1, 2, 3, 1, 2, 3).distinct().toArray());
 
Output:
[1, 2, 3]

 

10. IntStream to Array and List or Set


Use toArray() method to collect the output of IntStream into Array.
Use collect() method to collect the output of IntStream into List or Set.

To remove the duplicates from int stream, you can collect the results into Set rather than using distinct() method. But distinct() is recommended.
int[] intArray = IntStream.of(1, 2, 3, 1, 2, 3).toArray();
System.out.println("int array : "+Arrays.toString(intArray));


List<Integer> list = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toList());
System.out.println("IntStream to List : "+list);

Set<Integer> set = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toSet());
System.out.println("IntStream to Set : "+set);

 

11. Conclusion


In this article, we have seen all useful methods of IntStream with the useful examples.



How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?

1. Introduction


In this article, We'll learn how to compare two ArrayLists for checking Objects equality.


ArrayList has an equal() method that takes one argument type of Object. This equals() method compares the passed list object with the current list object. If both lists are having same values then it returns true, otherwise false. equals()

Read more on how to compare two strings lexicographically.

Example programs are shown on equals(), containsAll() and java 8 Stream API.

At the end of the article you will be good with comparing two lists and find differences between two lists in java


How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?


Java - How to Convert Java Array to Iterable?

1. Overview

In this tutorial, We will learn how to convert java array to iterable in different ways with example programs.

First we will go thorough the basic one how to iterate over the array values. Next, how to convert the array to Iterable using legacy java api and finally using java 8 api for java array iterator.

Bonus section on how to convert string to iterable with a delimiter.

Java - How to Convert Array to Iterable?



2. Create a iterator over the array using loops


Running a for loop over a array to create iterable logic to get the each value from array based on the index.
package com.javaprogramto.arrays.toiterabale;

/**
 * 
 * Array Iterate example using loops
 * 
 * @author javaprogramto.com
 *
 */
public class ArrayIterate {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};
		
		// iterating array over its values.
		for(int index=0; index< names.length ; index++) {
			System.out.println(names[index]);
		}
	}
}

 
Output:
john
Amal
Paul
 

3. Convert Java Array to Iterable using legacy java before JDK 8


First we will convert the array to list using Arrays.asList() method. Next, convert list to Iterable in java using list.iterator() method.

Finally, iterate the iterator over the while loop to get the all the values.

Array to Iterable Example:
package com.javaprogramto.arrays.toiterabale;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * Example to convert Java Array to Iterable before Java 8
 * 
 * @author javaprogramto.com
 *
 */
public class JavaArrayToIterableExample {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};
		
		// string array to list conversion
		List<String> namesList = Arrays.asList(names);
		
		// List to iterable
		Iterator<String> it = namesList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
}
 
Output:
john
Amal
Paul
 

4. Convert Java Array to Iterable Using Java 8 Stream


In the above section, we called Arrays.asList() method to convert the array to List. But, now will use another method from java 8 stream api Arrays.stream(array) method which takes input array and returns a Stream of array type.

Arrays.stream() method provides the arrays to access the stream api and use the power of parallel execution on larger arrays.

But for now, after getting the Stream<String> object then you need to call the iterator() method on stream to convert Stream to iterable.

Do not worry, if you are new to the java 8, the below program is break down into multiple steps. And also provided a single line solution.
import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.Stream;

/**
 * 
 * Example to convert Java Array to Iterable using Java 8 Arrays.stream()
 * 
 * @author javaprogramto.com
 *
 */
public class JavaArrayToIterableExampleJava8 {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};

		System.out.println("Multi line solution");
		// Convert string array to Stream<String>
		Stream<String> namesList = Arrays.stream(names);
		
		// Stream to iterable
		Iterator<String> it = namesList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		// singel line
		System.out.println("\nIn single line");
		Arrays.stream(names).iterator().forEachRemaining(name -> System.out.println(name));
	}
}
 

Multiline and single line solutions provide the same output. If you are going to use in the realtime project then use it as single line statement as you want to fell like expert and take the advantage of stream power.
Multi line solution
john
Amal
Paul

In single line
john
Amal
Paul

 

5. Bonus - Convert String to Iterable


Applying iterable on string is quite simple if you have understood the above code correctly. What we need is now to convert the String to String array with space or if the string has any delimiter.

After getting the string array then apply the same logic as java 8 streams as below.
public class JavaStringToIterableExampleJava9 {

	public static void main(String[] args) {

		// string 
		String numbers = "1 2 3 4 5 6";

		// string to string array
		String[] numbersArray = numbers.split(" ");

		System.out.println("Multi line solution");
		// Convert string array to Stream<String>
		Stream<String> numbersList = Arrays.stream(numbersArray);
		
		// Stream to iterable
		Iterator<String> it = numbersList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		// singel line
		System.out.println("\nIn single line");
		Arrays.stream(numbersArray).iterator().forEachRemaining(name -> System.out.println(name));
	}
}
 
Output:
Multi line solution
1
2
3
4
5
6

In single line
1
2
3
4
5
6

 

6. Conclusion


In this article, you've seen how to convert the Array to iterable and get the each value from iterator using legacy and new java 8 api.

And also how to convert String to Iterable in java?



الاثنين، 7 يونيو 2021

Java Convert File Contents to String

1. Overview

In this tutorial, you'll learn how to convert File contents to String in java.

If you are new to java 8, please read the how to read the file in java 8? we have already shown the different ways to read the file line by line.

Java new Files api has two useful methods to read the file.

readAllLines()
readAllBytes()

Let us write the examples on each method to convert file to string in java.

Java Convert File Contents to String


الجمعة، 4 يونيو 2021

Java - How to Delete Files and Folders?

1. Overview

In this tutorial, We will learn how to delete the files and folders in java.

Let us learn the example programs on file deletion and folder removal in java.

Java - How to Delete Files and Folders?


2. Java Files Delete Example

First, Use delete() method on the file object to delete the file. Returns true if the file is delete successfully and else return false if there are any failures.

In the below program, we have taken two files test.log file is present in the location and no-file.log does not exists on the location.

Let us see the behaviour of delete() method.


package com.javaprogramto.files.delete;

import java.io.File;

/**
 * How to delete the file in java using File api delete() method.
 * 
 * @author JavaProgramTo.com
 *
 */
public class FileDelete {

	public static void main(String[] args) {

		// File deletion success
		String fileName = "src/main/java/com/javaprogramto/files/delete/test.log";
		
		File file = new File(fileName);
		
		boolean isFileDeleted = file.delete();
		
		if(isFileDeleted) {
			System.out.println("File deleted without any errors for "+fileName);
		} else {
			System.out.println("File deletion is failed");
		}
		
		// File deletion error.
		
		fileName = "src/main/java/com/javaprogramto/files/delete/no-file.log";
		
		file = new File(fileName);
		
		isFileDeleted = file.delete();
		
		if(isFileDeleted) {
			System.out.println("File deleted without any errors for "+fileName);
		} else {
			System.out.println("File deletion is failed for "+fileName);
		}


	}

}
 

Output:

File deleted without any errors for src/main/java/com/javaprogramto/files/delete/test.log
File deletion is failed for src/main/java/com/javaprogramto/files/delete/no-file.log

 

3. Java Delete Folder Example

Next, we will try to delete the folder which is having the files and next empty folder deletion using delete() method.


package com.javaprogramto.files.delete;

import java.io.File;

/**
 * How to delete the folder in java using File API delete() method.
 * 
 * @author JavaProgramTo.com
 *
 */
public class FileDeleteFolder {

	public static void main(String[] args) {

		// Folder deletion not done
		String folderName = "src/main/java/com/javaprogramto/files/delete";
		
		File file = new File(folderName);
		
		boolean isFileDeleted = file.delete();
		
		if(isFileDeleted) {
			System.out.println("Folder with files is deleted");
		} else {
			System.out.println("Folder with files is not deleted");
		}
		
		// Empty Folder deletion success .
		
		folderName = "src/main/java/com/javaprogramto/files/emptyfolder";
		
		file = new File(folderName);
		
		isFileDeleted = file.delete();
		
		if(isFileDeleted) {
			System.out.println("Empty Folder deleted ");
		} else {
			System.out.println("Empty Folder deletion is failed for "+folderName);
		}
	}
}
 

Output:

Folder with files is not deleted
Empty Folder deleted 

 

Note: if the folder is empty then only folder will be deleted and folder which has files won't be deleted. But, we can delete the files folder after deleting all files.

4. Conclusion

In this article, we've seen how to delete the files and folder in java with examples.

GitHub

How to compress and decompress the files in java?

File.delete() API