Tuesday, February 28, 2023

Read or List All Files in a Folder in Java

In this post we'll see how to read or list all the files in a directory using Java. Suppose you have folder with files in it and there are sub-folders with files in those sub-folders and you want to read or list all the files in the folder recursively.

Here is a folder structure used in this post to read the files. Test, Test1 and Test2 are directories here and then you have files with in those directories.

Test
  abc.txt
  Test1
    test.txt
    test1.txt
  Test2
    xyz.txt

Java Example to read all the files in a folder recursively

There are two ways to list all the files in a folder; one is using the listFiles() method of the File class which is there in Java from 1.2.

Another way to list all the files in a folder is to use Files.walk() method which is a recent addition in Java 8.

 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;

public class ListFiles {
  public static void main(String[] args) {
    File folder = new File("G:\\Test");
    ListFiles listFiles = new ListFiles();
    System.out.println("reading files before Java8 - Using listFiles() method");
    listFiles.listAllFiles(folder);
    System.out.println("-------------------------------------------------");
    System.out.println("reading files Java8 - Using Files.walk() method");
    listFiles.listAllFiles("G:\\Test");

  }
  // Uses listFiles method  
  public void listAllFiles(File folder){
    System.out.println("In listAllfiles(File) method");
    File[] fileNames = folder.listFiles();
    for(File file : fileNames){
      // if directory call the same method again
      if(file.isDirectory()){
         listAllFiles(file);
      }else{
        try {
          readContent(file);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
  // Uses Files.walk method   
  public void listAllFiles(String path){
    System.out.println("In listAllfiles(String path) method");
    try(Stream<Path> paths = Files.walk(Paths.get(path))) {
      paths.forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
          try {
            readContent(filePath);
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      });
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   } 
  }
     
  public void readContent(File file) throws IOException{
    System.out.println("read file " + file.getCanonicalPath() );
    try(BufferedReader br  = new BufferedReader(new FileReader(file))){
      String strLine;
      // Read lines from the file, returns null when end of stream 
      // is reached
      while((strLine = br.readLine()) != null){
      System.out.println("Line is - " + strLine);
      }
    }
  }
     
  public void readContent(Path filePath) throws IOException{
    System.out.println("read file " + filePath);
    List<String> fileList = Files.readAllLines(filePath);
    System.out.println("" + fileList);
  }   
}

Output

reading files before Java8 - Using listFiles() method
In listAllfiles(File) method
read file G:\Test\abc.txt
Line is - This file is in Test folder.
In listAllfiles(File) method
read file G:\Test\Test1\test.txt
Line is - This file test is under Test1 folder.
read file G:\Test\Test1\test1.txt
Line is - This file test1 is under Test1 folder.
In listAllfiles(File) method
read file G:\Test\Test2\xyz.txt
Line is - This file xyz is under Test2 folder.
-------------------------------------------------
reading files Java8 - Using Files.walk() method
In listAllfiles(String path) method
read file G:\Test\abc.txt
[This file is in Test folder.]
read file G:\Test\Test1\test.txt
[This file test is under Test1 folder.]
read file G:\Test\Test1\test1.txt
[This file test1 is under Test1 folder.]
read file G:\Test\Test2\xyz.txt
[This file xyz is under Test2 folder.]

Here we have two overloaded listAllFiles() methods. First one takes File instance as argument and use that instance to read files using the File.listFiles() method. In that method while going through the list of files under a folder you check if the next element of the list is a file or a folder. If it is a folder then you recursively call the listAllFiles() method with that folder name. If it is a file you call the readContent() method to read the file using BufferedReader.

Another version of listAllFiles() method takes String as argument. In this method whole folder tree is traversed using the Files.walk() method. Here again you verify if it is a regular file then you call the readContent() method to read the file.

Note that readContent() method is also overloaded one takes File instance as argument and another Path instance as argument.

If you just want to list the files and sub-directories with in the directory then you can comment the readContent() method.

That's all for this topic Read or List All Files in a Folder in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Write to a File in Java
  2. How to Append to a File in Java
  3. How to Read File From The Last Line in Java
  4. How to Find Last Modified Date of a File in Java
  5. Unzip File in Java

You may also like-

  1. How to Create PDF From XML Using Apache FOP
  2. Print Odd-Even Numbers Using Threads And Semaphore Java Program
  3. How to Run Threads in Sequence in Java
  4. How to Display Pyramid Patterns in Java - Part1
  5. Add Double Quotes to a String Java Program
  6. Java Stream API Tutorial
  7. How HashMap Works Internally in Java
  8. Java ReentrantLock With Examples

Monday, February 27, 2023

Private Methods in Java Interface

Interfaces in Java were living the life of having public static final fields and public abstract methods till Java 7 but got a makeover with some new features added to them later namely-
  • Capability to add default methods to interface from Java 8 onward.
  • Capability to add static methods to interface from Java 8 onward.
  • Capability to add private methods to interface from Java 9 onward.

In this post we’ll see how to add private methods to a Java interface, what is the reason to include private methods to an interface.

Private methods in Java interface

Private methods in Java interfaces are defined using private modifier the same way it is done for a Java class.

private methodName(argument_List){
 ..
 ..
}

Private methods in Java interface can be both static and non-static.

Reason to include private methods to an interface in Java

Java 8 included interface default methods and interface static methods to an interface with that inclusion it became possible to write method bodies with in an interface but a new problem was observed.

Let’s say you have 2 methods and both of them share some code and you want to write that code as a separate method which can be called from both the methods. In Java 8 that method with common code could be default or static.

Here note that both default and static methods with in a Java interface are public by default meaning the method having common code would also be implicitly public. Which means any class implementing the interface can access this method too. But that method has some code which makes sense with in the interface, calling it from any other class doesn’t make sense and it is also against the encapsulation OOPS concept because access is given to some method which is not at all required.

Let’s try to understand this scenario in Java 8 with an example-

public interface TestInterface {
 default void defMethod1(){
  sharedCode();
  System.out.println("In default method 1");
 }
 
 default void defMethod2(){
  sharedCode();
  System.out.println("In default method 2");
 }
 
 default void sharedCode(){
  System.out.println("In sharedCode, invoking it on its own"
    + " doesn't make much sense");
 }
}

As you can see in the Interface there are two default methods defMethod1() and defMethod2() in the interface. Common code executed by both the methods is kept in a separate default method to avoid duplication of the code.

But the problem with this interface is that any class implementing this interface could access sharedCode() method too as all the methods were public by default till Java 8.

public class TestClass implements TestInterface {
  public static void main(String[] args) { 
   TestClass obj = new TestClass();
   obj.sharedCode();
  }
}

Output

In sharedCode, invoking it on its own doesn't make much sense

Interface private methods Java 9 onward

With the new feature of private methods in interfaces from Java 9 onward such methods (as shown in the above example) can be written as private methods which are not visible outside the interface. That way code redundancy can be avoided while keeping the access to the method restricted.

The example showed above can use private access modifier (Java 9 onward) with the sharedCode() method with in the interface to keep access to it restricted.

public interface TestInterface {
 default void defMethod1(){
  sharedCode();
  System.out.println("In default method 1");
 }
 
 default void defMethod2(){
  sharedCode();
  System.out.println("In default method 2");
 }
 
 private void sharedCode(){
  System.out.println("In sharedCode, invoking it on its own"
    + " doesn't make much sense");
 }
}

Now trying to access sharedCode() method from a class implementing this interface will result in compile time error “The method sharedCode() is undefined for the type TestClass”.

public class TestClass implements TestInterface {
  public static void main(String[] args) { 
   TestClass obj = new TestClass();
   obj.sharedCode(); // Compiler error
  }
}
Now you can invoke default method from the implementing class which in turn invokes the private method.
public class TestClass implements TestInterface {
  public static void main(String[] args) { 
   TestClass obj = new TestClass();
   obj.defMethod1();
  }
}

Output

In sharedCode, invoking it on its own doesn't make much sense
In default method 1

As you can see now private method can be accessed through methods of the interfaces only.

Rules for private methods in Java interfaces

The usage of private methods in the Java interfaces is guided by the following rules-

  1. Private methods in an interface can't be abstract they should have method body. Trying to define a private method as a regular public abstract method in an interface results in the error "This method requires a body instead of a semicolon"
  2. If you want to invoke a private method from a static method in an interface then you should write a private static method. From a static context you cannot access a non-static method it will give you an error “Cannot make a static reference to the non-static method”.
  3. A default method in an interface can invoke both static and non-static private methods with in an interface.

That's all for this topic Private Methods in Java Interface. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. New Date And Time API in Java With Examples
  4. PermGen Space Removal in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. How and Why to Synchronize ArrayList in Java
  2. How HashMap Internally Works in Java
  3. ConcurrentHashMap in Java With Examples
  4. String Comparison in Java equals(), compareTo(), startsWith() Methods
  5. Java Exception Handling And Method Overriding
  6. Java Program to Find First Non-Repeated Character in a Given String
  7. Bean Scopes in Spring With Examples
  8. Data Compression in Hadoop

Sunday, February 26, 2023

Spring MVC @PathVariable Example - Creating Dynamic URL

In this Spring web MVC example we’ll see how request data can be passed to the controller using @PathVariable annotation along with @RequestMapping annotation.


Spring @RequestMapping with @PathVariable annotation

If you are passing parameters as the part of the request path, for example spring-mvc/getUser/101 then you can use @PathVariable annotation to retrieve the parameter from the request path. @RequestMapping annotation will have a placeholder to match the parameter with in the URL. That way you can pass dynamic URLs in your Spring MVC application where the place holder part of the URL can vary.

Spring web MVC example with @PathVariable annotation

In this Spring MVC example we’ll have a JSP (home page) from where the entered userId is sent in the request path.

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - Home JSP</title>

</head>

<body>
<script type="text/javascript">
function OnSubmitForm()
{
   var userid = document.getElementById("userid").value;
   document.userform.action="getUser/"+userid;
   return true;
}
</script>
    <h1>Hello World!</h1>
    <h4>Message- </h4><span>${message}</span>
    <form name="userform" method="post" onsubmit="return OnSubmitForm();">         
          User ID: <input type="text" id="userid" name="userid">                        
         <input type="submit" value="Submit">
    </form>
</body>
</html>

In the JSP, at the time of submitting the form userId is added to the action, using the Java script function, so that the URL has the userID too.

Spring MVC @PathVariable example - Controller class

The controller method with the appropriate @RequestMapping with a placeholder for userId will handle this request. With in the controller method there is also a @PathVariable annotation with a parameter. The value matching the placeholder is assigned to this parameter.

@Controller
public class MessageController {
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String showHome(Model model) {
  //model.addAttribute(new User());
  model.addAttribute("message", "MVC Example with dynamic URL");
  return "home";
 }
 
 @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
 public String getUser(@PathVariable("userId") String userId, Model model) {
  // adding the user object to model
  // ideally get it from DB
  model.addAttribute("USER", findUserById(userId));
  return "user";
 }
 
 // Dummy Method-- Creating user object
 private User findUserById(String userId) {
  System.out.println("User ID " + userId);
  User user = new User();
  user.setUserId(userId);
  user.setFirstName("Leonard");
  user.setLastName("Nimoy");
  return user;
 }
}

As you can see in the Controller class there is a method getUser() with @RequestMapping annotation having the value as "/getUser/{userId}". Here {userId} part is the placeholder. Also there is a @PathVariable annotation with the matching value as the placeholder - @PathVariable("userId") and a parameter userId. A URL in the following form /getUser/101 will be matched to the @RequestMapping, Spring framework looks for the @PathVariable having the same value parameter as the placeholder. If found the parameter annotated with the @PathVariable annotation is assigned the value in placeholder.

Note that if method parameter name is same as the placeholder name in the @RequestMapping then the value parameter on @PathVariable is optional. So the same method can also be written as-

@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
public String getUser(@PathVariable String userId, Model model) {
 
}

Once you have the userId, you can fetch user details using that ID from DB. Here we have dummy method to create a User object. That user object is then set into the Model. The returned logical view name is “user” that resolves to another JSP called user.jsp where the bound user object fields are displayed.

User.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - User</title>
</head>
<body>
<div>First Name: ${USER.firstName}</div>
<div>Last Name: ${USER.lastName}</div>
</body>
</html> 

Model Bean – Spring MVC @PathVariable example

The model bean used here is as follows.

public class User {
 private String firstName;
 private String lastName;
 private String userId;
 public String getUserId() {
  return userId;
 }
 public void setUserId(String userId) {
  this.userId = userId;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}

Home page

Spring MVC @PathVariable example

User page

Spring MVC @PathVariable example

Having more than one @PathVariable annotations

You can have more than one placeholders matching more than one parameters in the request path and more than one @PathVariable annotations with method parameters corresponding to those placeholders. For example-

@RequestMapping(value = "/getUser/{firstName}/{lastName}", method = RequestMethod.GET)
public String getUserByName(@PathVariable String firstName, @PathVariable String lastName, Model model) {
 ...
 ...
}

@RequestMapping with regular expression

If you want to put some constraint on the placeholder matching with in the @RequestMapping annotation you can use regular expressions to define the placeholder. For example- If you want to ensure that userId has to be 4 digits.

@RequestMapping(value = "/getUser/{userId:\\d{4}}", method = RequestMethod.GET)
public String getUser(@PathVariable("userId") String userId, Model model) {

}

That's all for this topic Spring MVC @PathVariable Example - Creating Dynamic URL. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Web MVC Tutorial
  2. Spring Web MVC Java Configuration Example
  3. Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation
  4. Spring MVC PDF Generation Example
  5. Transaction Management in Spring

You may also like-

  1. Spring Transaction Attributes - Propagation And Isolation Level Settings
  2. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  3. registerShutdownHook() Method in Spring Framework
  4. Circular Dependency in Spring Framework
  5. Difference Between Encapsulation And Abstraction in Java
  6. Java Collections Interview Questions And Answers
  7. How to Remove Duplicate Elements From an ArrayList in Java
  8. Java Object Cloning - clone() Method

Saturday, February 25, 2023

Reverse Each Word in a String Java Program

Write a Java program to reverse a String is asked in many interviews, there is another version similar to it where developers are asked to write a Java program to reverse each word of a given String.

If you notice the Java program to reverse each word of a String is a combination of two programs- How to split a string in Java and how to reverse a String.

Java program to reverse each word in a String

First the passed string is split using split() method of the String class that returns an array having the words. Then iterate through the array and reverse each word, keep appending each reversed word to another string.

For reversing a String there are both recursive and iterative logic, in the code both are shown.

public class ReverseWord {

  public static void main(String[] args) {
    // /Using recursive logic
    String str = "Reverse each word of this string";
    StringBuilder sb = new StringBuilder();
    // For splitting on spaces
    String[] strArr = str.split("\\s+");
    // reversing and appending to StringBuffer
    for(String s : strArr) {
      sb.append(reverseString(s)).append(" ");
    }
    System.out.println("Original String- " + str);
    System.out.println("Reversed String- " + sb.toString());
    
    // Using iterative logic
    str = "This is reverse program";
    sb = new StringBuilder();
    strArr = str.split("\\s+");
    for(String s : strArr) {
      sb.append(reverseStringItr(s)).append(" ");
    }
    System.out.println("Original String- " + str);
    System.out.println("Reversed String- " + sb.toString());
  }
    
  // Recursive logic to reverse a String
  private static String reverseString(String str) {
    // validation & base case
    if((str == null) || (str.length() <= 1)){
      return str;
    }
    // recursive call
    return reverseString(str.substring(1)) + str.charAt(0);  
  }
    
  // Using iteration - Non Recursive
  private static String reverseStringItr(String str){
    // validation
    if((str == null) || (str.length() <= 1)){
      return str;
    }
    
    StringBuilder sb = new StringBuilder();
    for(int i = str.length() - 1; i >= 0; i--){
      sb.append(str.charAt(i));
    }
    return sb.toString();
  }
}

Output

Original String- Reverse each word of this string
Reversed String- esreveR hcae drow fo siht gnirts 
Original String- This is reverse program
Reversed String- sihT si esrever margorp 

That's all for this topic Reverse Each Word in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Converting Char to String And String to Char in Java
  3. Find Duplicate Characters in a String With Repetition Count Java Program
  4. Java Program to Reverse a Number
  5. Find The Maximum Element in Each Row of The Matrix - Java Program

You may also like-

  1. Java Lambda Expression Callable Example
  2. How to Read Properties File in Java
  3. How to Display Time in AM-PM Format in Java
  4. Running Dos/Windows Commands From Java Program
  5. How ArrayList Works Internally in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Access Modifiers in Java - Public, Private, Protected and Default
  8. How MapReduce Works in Hadoop

Tuesday, February 14, 2023

JavaScript Array reduce() Method With Examples

The JavaScript Array reduce() method executes a reducer function (a callback function) on each element of the array and returns a single value (reduces the array elements to a single value).

Syntax of reduce method

reduce(callbackFunction, initialValue)

// Callback function definition
function callbackFunction(accumulator, currentValue) {
  return FINAL_VALUE;
}

If written as arrow function

reduce((accumulator, currentValue) => { /* … */ }, initialValue)

Parameters

  1. callbackFunction- A function to execute for each element in the array. The return value in each call to callback function becomes the value of the accumulator parameter on the next invocation of callback function.

    The callback function is called with the following arguments:

    • accumulator- Accumulates the callback function's return values. At any time it stores the value resulting from the previous call to callback function.
    • currentValue- The value of the current element passed from the array.
  2. initialValue- It is an optional parameter. If passed then accumulator is initialized to the initialValue the first time callback function is called. Then callback function starts executing with the first value in the array as currentValue.
    If initialValue is not specified, accumulator is initialized to the first value in the array, and callback function starts executing with the second value in the array as currentValue.

Reduce method JavaScript example

1. Using reduce to sum all elements in an array.

const numArr = [4, 5, 6, 7, 8, 9];
const sum = numArr.reduce((accumulator, element) => accumulator + element);
console.log(sum); // 39

Same example when written with an explicit callback function.

const numArr = [4, 5, 6, 7, 8, 9];
const sum = numArr.reduce(sumFun);
console.log(sum);//39
//callback function
function sumFun(accumulator, element) {
  return accumulator + element
}

Let's try to understand how does reducer function work with the above example. As you know accumulator stores the return value of the function.

When the function is run for the first time there is no return value of the previous calculation. So, in first iteration, if initialValue is passed then that is stored in the accumulator otherwise the array element at index 0 is stored.

In our example there is no initialValue, so accumulator has numArr[0] which means 4 and currentValue is numArr[1] which means 5, in the first iteration. Return value is 9.

In the second iteration accumulator has the return value of the previous iteration which means 9 and currentValue is numArr[2] which means 6. Return value is 15.

Same procedure is followed in other iterations.

2. Using reduce to sum all elements in an array, when an initial value is also passed.

const numArr = [4, 5, 6, 7, 8, 9];
const sum = numArr.reduce((accumulator, element) => accumulator + element, 10);
console.log(sum);  // 49

Since there is an initial value now, so that is stored in the accumulator in the first iteration and currentValue stored numArr[0].

3. Counting occurrence of each element in an array and storing them in an object.

const numArr = [100, 2, 4, 100, 6, 1, 4, 1, 6];
const elementCount = numArr.reduce((numCount, num) => {
  let count = numCount[num] > 0 ? numCount[num] : 0;
  numCount[num] = ++count;
  return numCount;
}, {});
console.log(elementCount); // {1: 2, 2: 1, 4: 2, 6: 2, 100: 2}

4. Group objects by one of the object properties. In this example we have an array of Person objects which will be grouped on gender property. Note that spread operator is used to expand the array.

const persons = [{id:1, name:"Ajay", gender:"M"}, 
   {id:2, name:"Rajiv", gender:"M"}, 
   {id:3, name:"Bethany", gender:"F"},
   {id:4, name:"Albert", gender:"M"}, 
   {id:5, name:"Amy", gender:"F"},];
   
function groupObjectsByProperty(array, property){
  return array.reduce((accumulator, personObj) => {
    let groupingKey = personObj[property];
    let grp = !accumulator[groupingKey] ? [] : accumulator[groupingKey];
    return { ...accumulator, [groupingKey]: [...grp, personObj] };
  }, {});
}

// Function call
const groupedPeople = groupObjectsByProperty(persons, "gender");
console.log(groupedPeople);

Output

{
 F: [
	{id: 3, name: 'Bethany', gender: 'F'}.
	{id: 5, name: 'Amy', gender: 'F'}
 ],
  M: [
	{id: 1, name: 'Ajay', gender: 'M'},
	{id: 2, name: 'Rajiv', gender: 'M'},
	{id: 4, name: 'Albert', gender: 'M'}
 ]
}

That's all for this topic JavaScript Array reduce() Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array map() Method With Examples
  2. JavaScript Array slice() method With Examples
  3. JavaScript Arrow Function With Examples
  4. React HelloWorld App - First React App
  5. React create-react-app Project Structure

You may also like-

  1. Unmodifiable or Immutable List in Java
  2. Reverse Each Word in a String Java Program
  3. this Keyword in Java With Examples
  4. Constructor in Python - __init__() function
  5. BeanPostProcessor in Spring Framework