Wednesday, August 31, 2022

Java trim(), strip() - Removing Spaces From String

In this post we’ll see what all options are there in Java String class to remove leading, trailing spaces from a String, even spaces from in between the words in a String.

String class methods for removing spaces

  • trim()- Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020'
  • strip()- Java 11 onward there is also a strip() method which does the same task of removing all leading and trailing white spaces. How it differs from trim() is that in strip() method whether the specified character is white space or not is determined by internally using Character.isWhitespace() method which also considers unicodes like \u2007, \u202F as whitespaces (greater than 'U+0020')
  • stripLeading()- Variant of strip() method that removes all leading white spaces.
  • stripTrailing()- Variant of strip() method that removes all trailing white spaces.
  • replaceAll()- To remove spaces any where in a string; leading, trailing or between words replaceAll() method can be used with regular expression “\\s+” as parameter to match any numbers of spaces anywhere.

Removing spaces from Java string examples

Let us see examples using the methods mentioned above.

1. Using trim() method to remove spaces from a String in Java. This method removes leading and trailing spaces not the spaces between words.

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example String ";
  str = str.trim();
  System.out.println("String- " + str);
 }
}

Output

String- Example   String

2. Using strip() method to remove spaces. This method is added in Java 11 and it takes into account unicodes categorized as space separator having value greater than '\u0020

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = '\u2001'+"Example String";
  System.out.println("String- " + str);
  System.out.println("String after trim- " + str.trim());
  str = str.strip();
  System.out.println("String after strip- " + str);
 }
}

Output

String-  Example String
String after trim-  Example String
String after strip- Example String

As you can see trim() method is not able to remove space created by ‘\u2001’ but strip() method could.

3. If you have to remove all the spaces; leading, trailing and spaces between the words then you can use replaceAll() method.

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example   String   ";
  // regex to match any number of spaces
  str = str.replaceAll("\\s+", "");
  System.out.println(str);
 }
}

Output

ExampleString

That's all for this topic Java trim(), strip() - Removing Spaces From String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Compact Strings in Java
  2. Check String Null or Empty in Java
  3. String Comparison in Java equals(), compareTo(), startsWith() Methods
  4. Java Program to Find The Longest Palindrome in a Given String
  5. Java String Interview Questions And Answers

You may also like-

  1. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  2. Creating Custom Exception Class in Java
  3. Java Pass by Value or Pass by Reference
  4. ArrayList in Java With Examples
  5. Java StampedLock With Examples
  6. Optional Class in Java With Examples
  7. Namespace And Variable Scope in Python
  8. Spring Object XML Mapping (OXM) JAXB Example

Tuesday, August 30, 2022

Converting String to Char Array in Java

This Java program shows how you can convert String to char array in Java. In Java String class there is a method toCharArray() that is used for the purpose. This method returns a character array whose length is the length of this string and the array is initialized to contain the character sequence represented by this string.

Convert String to char[] in Java

public class StringToCharArray {

 public static void main(String[] args) {
  String str = "Test String";
  // Converting to char array
  char[] charArray = str.toCharArray();
  // Accessing each character
  for(Character c : charArray)
   System.out.println(c);
 }
}

Output

T
e
s
t
 
S
t
r
i
n
g

That's all for this topic Converting String to Char Array 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. Convert String to Byte Array Java Program
  2. Converting Char to String And String to Char in Java
  3. Add Double Quotes to a String Java Program
  4. Convert float to String in Java
  5. Convert Numbers to Words Java Program

You may also like-

  1. Converting Enum to String in Java
  2. Binary Search Program in Java
  3. Shell Sort Program in Java
  4. How to Convert Date to String in Java
  5. Difference Between ArrayList And LinkedList in Java
  6. Java Exchanger With Examples
  7. Transaction Management in Spring
  8. Python String split() Method

Monday, August 29, 2022

Fix Scanner.nextLine() Skipping Input After Another next Methods

In this article we’ll see why do we have the issue of Scanner.nextLine() skipping the input if used just after any other next method of the java.util.Scanner class and how to fix this problem.

What is the problem

If you are here to look for a solution to this problem you might already have encountered a similar scenario. Here is a program where next() method of the Scanner class is used to get a word as input, then nextLine() is used, then nextInt() and again nextLine() is used.

import java.util.Scanner;

public class ScannerDemo {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a word: ");
		String s = sc.next();
		
		System.out.println("Enter name: ");
		String name = sc.nextLine();
		
		System.out.println("Enter a number: ");
		int i = sc.nextInt();
		
		System.out.println("Enter address: ");
		String addr = sc.nextLine();
		
		System.out.println("Entered word is- " + s);
		System.out.println("Entered name is- " + name);
		System.out.println("Entered number is- " + i);
		System.out.println("Entered address is- " + addr);
	}

}

Output

Enter a word: 
test
Enter name: 
Enter a number: 
1
Enter address: 
Entered word is- test
Entered name is- 
Entered number is- 1
Entered address is- 

As you can see both nextLine() methods are skipped here.

What is the reason of skipping

When you use any of the next method be it next(), nextInt() etc. The input is read till the content ends without reading the newline character which is there because of pressing "enter".

If there is a nextLine() method just after any of the other next methods of the Scanner class, it ends up reading just the newline character (‘\n’) left by the previous next method usage.

As per the documentation of the nextLine() method in Scanner.

Advances this scanner past the current line and returns the input that was skipped.

In the scenario of using it after any other next method it advances past the left over newline character and returns just that input. So it seems, as if nextLine() is skipped.

How to fix this issue

Simple solution is to use an extra nextLine() method in such scenario to consume the left over new line character ('\n') so that the following nextLine() can take the actual input from the user. If we do that to the program used as example previously.

public class ScannerDemo {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a word: ");
		String s = sc.next();
		// extra nextLine
		sc.nextLine();
		System.out.println("Enter name: ");
		String name = sc.nextLine();
		
		System.out.println("Enter a number: ");
		int i = sc.nextInt();
		
		sc.nextLine();
		System.out.println("Enter address: ");
		String addr = sc.nextLine();
		
		System.out.println("Entered word is- " + s);
		System.out.println("Entered name is- " + name);
		System.out.println("Entered number is- " + i);
		System.out.println("Entered address is- " + addr);
	}
}

Output

Enter a word: 
test
Enter name: 
Ramesh Jaiswal
Enter a number: 
10
Enter address: 
1 VIP Road, New Delhi
Entered word is- test
Entered name is- Ramesh Jaiswal
Entered number is- 10
Entered address is- 1 VIP Road, New Delhi

As you can see with the inclusion of two extra sc.nextLine() methods problem of Scanner.nextLine() method skipping the input is solved.

That's all for this topic Fix Scanner.nextLine() Skipping Input After Another next Methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  2. Buffered Streams in Java IO
  3. How to Read Input From Console in Java
  4. Read File Asynchronously Java Program
  5. Java Program to Delete File And Directory Recursively

You may also like-

  1. Difference Between StackOverflowError and OutOfMemoryError in Java
  2. How to Get The Inserted ID (Generated ID) in JDBC
  3. Java Concurrency Interview Questions And Answers
  4. Static Synchronization in Java Multi-Threading
  5. Spring MVC Generate Response as JSON Example
  6. registerShutdownHook() Method in Spring Framework
  7. Global Keyword in Python With Examples
  8. Angular One-Way Data Binding Using String Interpolation

Sunday, August 28, 2022

Navigate to a Route Programmatically in Angular

In this post we’ll see how to navigate to a route programmatically or dynamically using router.navigate() or router.navigateByUrl() methods in Angular.

Navigating to a route dynamically Angular example

You may have a scenario where you would like to navigate to a route based on an event like click of a button, clicking a link. Here is a simple example which uses router.navigate() method to navigate to a route on a click of a button.

Note that while navigating to a route you can use both absolute as well as relative path. In this post we'll see examples of both.

There is a menu as shown below and you have to show the corresponding component on click of the menu option.

1. Creating routing module

We’ll create a separate routing file app-routing.module.ts with routes array to define route paths and component they map to.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';


const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. Import the AppRoutingModule into AppModule (app.module.ts) and add it to the imports array.

import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],

3. Adding the configured routes to the application.

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
          <a class="nav-link" routerLink="/">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Creating components

Now as per our route mapping there are 3 components HomeComponent, AccountsComponent and ServiceComponent.

Home Component (home.component.ts)

From the home page you want to provide a button to take to AccountsComponent. That route navigation will be done programmatically.

import { OnInit, Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  userId = 'UID0023';
  constructor(private router: Router) { }

  ngOnInit() {
  }

  navigateToAccount(){
    this.router.navigate(['/account']);
  }
}

To use Router.navigate method first you need to inject the Router class in your component. That is done in the constructor.

In the method navigateToAccount(), router.navigate() method is used to navigate to a route. In navigate method you pass an array of elements that are joined together to create a path. For example router.navigate(‘account’, 1) resolves to a path /account/1.

If you want to use router.navigateByUrl() method then you can also use this.router.navigateByUrl('/account'); With router.navigateByUrl() you can pass an absolute path, for example router.navigateByUrl(‘/account/1’).

Note that in this example path passed in this.router.navigate(['/account']); is an absolute path (not relative).

home.component.html

<h4>Welcome to XYZ Bank</h4>
<p>{{ userId }} logged in.</p>
<div>
    <button type="button" class="btn btn-primary" (click)="navigateToAccount()">My Accounts</button>
</div>

Account Component (account.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
}

accounts.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <!-- [routerLink]="" 
    (click)="onAccountClick(account)" -->
    <div class="list-group">
      <a class="list-group-item"   
        *ngFor="let account of accounts">
        {{ account }}
      </a>
    </div>
  </div>
</div>

Service Component (service.component.ts)

import { Component } from "@angular/core";

@Component({
  selector: 'app-service',
  templateUrl:'./service.component.html'
})
export class ServiceComponent{
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ]; 
}

service.component.html

<h2>Services Offered</h2>
<div class="row">
  <div class="col-xs-12 col-sm-6">
    <div class="list-group">
      <a
        href="#"
        class="list-group-item"
        *ngFor="let service of services">
        {{ service }}
      </a>
    </div>
  </div>
</div>

Add these components in the declarations array of the AppModule before running the example.

You will have a button in the HomeComponent which navigates you to the AccountsComponent when clicked.

Navigate to a Route Programmatically in Angular

Dynamic route Navigation using relative path in Angular

In the previous example we used absolute path with navigate() method but you can also pass a relative path but in that case you need to specify path is relative to which existing path.

Let’s change the previous example to have one more component AccountComponent that shows the details for the account selected in AccountsComponent.

For that routes array will have to be changed in the following way-

const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'account/:acctno', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

As you can see a new route definition is added- {path: 'account/:acctno', component: AccountComponent}, here :acctno is a placeholder that matches any account number so URL like account/A001 or account/A002 both will match this route.

Accounts component is also changed-

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
  constructor(private router: Router, private route: ActivatedRoute) {}
  onAccountClick(account: string){
    this.router.navigate([account], {relativeTo:this.route});
  }
}

Along with Router class now ActivatedRoute class is also injected into the component. ActivatedRoute class provides access to information about a route associated with a component that is loaded in router outlet.

In router.navigate() method you can also pass a second argument of type navigationExtras. One of the NavigationExtras is relativeTo which specifies a root URI to use for relative navigation.

In the example navigate method is now like this-

this.router.navigate([account], {relativeTo:this.route});

Here this.route specifies the route associated with the component, in our case it will be /account so relative path is http://localhost:4200/account

[account] specifies the account number that is clicked which can be either A1001 or A1002. Thus the navigation route is derived as either http://localhost:4200/account/A1001 or http://localhost:4200/account/A1002 which matches the route definition {path: 'account/:acctno', component: AccountComponent}.

AccountComponent (account.component.ts)

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    this.acctNo = this.route.snapshot.params['acctno'];
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }
}

Here we have defined an account type- account: {accountnumber: string, type: string, balance: number};

There is also an array with values for account.

In ngOnInit() using the passed account number we find the related object in the array using the find() method.

Account number parameter is extracted from the route using the current snapshot of the route.

this.route.snapshot.params['acctno'];

account.component.html

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>

Accounts Component

Account Component

navigating route dynamically angular

That's all for this topic Navigate to a Route Programmatically in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Setting and Fetching Route Parameters in Angular
  4. Setting Wild Card Route in Angular
  5. Nested Route (Child Route) in Angular

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. How to Create a Custom Observable in Angular
  3. Angular Event Binding With Examples
  4. Angular ngFor Directive With Examples
  5. Java Lambda Expression And Variable Scope
  6. Serialization and Deserialization in Java
  7. String Slicing in Python
  8. How to Untar a File - Java Program

Saturday, August 27, 2022

Angular Route Parameters - Setting and Fetching

In this post we’ll see how to pass and retrieve route parameters in Angular routing.


Route parameters in Angular

In our web apps we do need to navigate to a specific resource. For example we want the details of a specific account number then we can navigate to that account number by using URL- /account/A1001 or to another account by using URL- /account/A1002.

It is not practical to hardcode the path segment for each account number, you will use a route parameter instead that acts as a placeholder. Value passed for the placeholder becomes the value of the route parameter.

In a route that takes a parameter, route parameter is specified by prefixing it with a colon. So the route definition will be like- /route/:routeparam

You can pass more than one route parameter too- /route/:param1/:param2/:param3

For example if you have to a give route definition for a route- /account/A1001 where /A1001 part represents an account number and should be passed as a route parameter.

{path: 'account/:acctno', component: COMPONENT_NAME}

Passing Route parameters in Angular

1. You can pass route parameters with RouterLink directive. For a dynamic link, pass an array of path segments (which includes path and route parameters). For example

[routerLink]="['/account', accountnumber]"     

generates a link to /account/A1001 or to /account/A1002 based on what is passed as value for the string variable accountnumber.

2. You can also pass route parameters programmatically using Router.navigate() method. For example onAccountClick() method is called with account number as argument and then it creates a URL with route parameter using navigate() method. Here account number gets added as a route parameter to the current route.

onAccountClick(accountNo: string){
  this.router.navigate([accountNo], {relativeTo:this.route});
}

Retrieving route parameters in Angular

To extract the parameter, params observable of the ActivatedRoute interface is used and we subscribe to it so that when ever there is a change in the route parameter it is extracted into a variable.

this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);

Here value passed in acctno route parameter is assigned to acctNo variable. You can also extract parameter from the route using the current snapshot of the route.

this.acctNo = this.route.snapshot.params['acctno'];

Route parameters in Angular example

In the example we show user a list of account numbers. Then the details of the account number, that is clicked, are showed using a separate component. In this scenario you can pass the clicked account number as route parameter.

Here are the route definitions for the routes. Here AccountsComponent displays all the account numbers for a user and AccountComponent shows details for the selected account number.

const routes: Routes = [
                        {path: 'home', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'account/:acctno', component: AccountComponent},
                        {path: 'service', component: ServiceComponent},
                        {path: '', redirectTo:'/home', pathMatch: 'full'}                  
];

As you can see there is a route with route parameter- {path: 'account/:acctno', component: AccountComponent}

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Components

We’ll concentrate here on AccountsComponent and AccountComponent for the code of other components please refer- Angular Routing Concepts With Example.

AccountsComponent (accounts.component.ts)

In the component we have an array to show account numbers and a method onAccountClick() to navigate programmatically to a route.

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
  constructor(private router: Router, private route: ActivatedRoute) {}
  onAccountClick(account: string){
    this.router.navigate([account], {relativeTo:this.route});
  }
}

Two classes Router class and ActivatedRoute class are injected into the component.

  • Router class has navigate() method using which we navigate to a URL dynamically.
  • ActivatedRoute class provides access to information about the current route.

This line of code instructs Angular to navigate to the path which is relative to current route (localhost:4200/account in our example) and adds the value of account to it making it a route in this format- http://localhost:4200/account/ACCOUNT_NUMBER

this.router.navigate([account], {relativeTo:this.route});

Since we already have a route definition with a route parameter {path: 'account/:acctno', component: AccountComponent} which matches any route in this format http://localhost:4200/account/ACCOUNT_NUMBER so that’s how AccountComponent gets called.

accounts.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="" 
        (click)="onAccountClick(account)" 
        class="list-group-item"   
        *ngFor="let account of accounts">
        {{ account }}
      </a>
    </div>
  </div>
</div>

If you want to use RouterLink directive then your template can be written as-

  <div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="['/account', account]" class="list-group-item"  
        *ngFor="let account of accounts">
        
        {{ account }}
      </a>
    </div>
  </div>
</div>
  

In this case onAccountClick() method can be removed from typescript code as navigation is configured in the template itself.

AccountComponent (account.component.ts)

In this component we simulate a scenario where we have details for all the account numbers and we have to get the details for the account number which is sent as route parameter.

To extract the parameter route.params observable is used and we subscribe to it so that whenever there is a change, value of the parameter is extracted into a acctNo variable. Using the fetched account number we find the related object in the array using the find() method.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    //this.acctNo = this.route.snapshot.params['acctno'];
    this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }
}

Note that you can also extract parameter from the route using the current snapshot of the route. But route.params observable is preferred.

this.acctNo = this.route.snapshot.params['acctno'];

account.component.html

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>

Accounts Component

Account Component

That's all for this topic Angular Route Parameters - Setting and Fetching. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Passing Query Parameters in Angular Routing
  2. Path Redirection in Angular Routing
  3. Navigate to a Route Programmatically in Angular
  4. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  5. Angular CanActivateChild Guard to protect Child Routes

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular ngSwitch Directive With Examples
  3. Angular @Input and @Output Example
  4. How to Add Bootstrap to Angular Application
  5. PriorityBlockingQueue in Java Concurrency
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Predefined Mapper And Reducer Classes in Hadoop
  8. Passing Arguments to getBean() Method in Spring

Friday, August 26, 2022

How to Untar a File in Java

In this post we'll see a Java program showing how to untar a tar file. It has both the steps to first decompress a .tar.gz file and later untar it.

Using Apache Commons Compress

Apache Commons Compress library is used in the code for untarring a file. You can download it from here \– https://commons.apache.org/proper/commons-compress/download_compress.cgi.

Make sure to add commons-compress-xxx.jar in your application’s class path. I have used commons-compress-1.13 version.

Java example to untar a file

This Java program has two methods deCompressGZipFile() method is used to decompress a .tar.gz file to get a .tar file. Using unTarFile() method this .tar file is untarred.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;

public class UnTarDemo {
  public static void main(String[] args) {
    // Path to input file, which is a 
    // tar file compressed to create gzip file
    String INPUT_FILE = "G:\\Test.tar.gz";
    // This folder should exist, that's where
    // .tar file will go
    String TAR_FOLDER = "G:\\TarFile";
    // After untar files will go to this folder
    String DESTINATION_FOLDER = "G:\\Temp";
    UnTarDemo unTarDemo = new UnTarDemo();
    try {
      File inputFile = new File(INPUT_FILE);
      String outputFile = getFileName(inputFile, TAR_FOLDER);
      System.out.println("outputFile " + outputFile);
      File tarFile = new File(outputFile);
      // Calling method to decompress file
      tarFile = unTarDemo.deCompressGZipFile(inputFile, tarFile);
      File destFile = new File(DESTINATION_FOLDER);
      if(!destFile.exists()){
        destFile.mkdir();
      }
      // Calling method to untar file
      unTarDemo.unTarFile(tarFile, destFile);            
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  /**
   * 
   * @param tarFile
   * @param destFile
   * @throws IOException
   */
  private void unTarFile(File tarFile, File destFile) throws IOException{
    FileInputStream fis = new FileInputStream(tarFile);
    TarArchiveInputStream tis = new TarArchiveInputStream(fis);
    TarArchiveEntry tarEntry = null;
        
    // tarIn is a TarArchiveInputStream
    while ((tarEntry = tis.getNextTarEntry()) != null) {
      File outputFile = new File(destFile + File.separator + tarEntry.getName());        
      if(tarEntry.isDirectory()){            
        System.out.println("outputFile Directory ---- " 
            + outputFile.getAbsolutePath());
        if(!outputFile.exists()){
          outputFile.mkdirs();
        }
      }else{
        //File outputFile = new File(destFile + File.separator + tarEntry.getName());
        System.out.println("outputFile File ---- " + outputFile.getAbsolutePath());
        outputFile.getParentFile().mkdirs();
        //outputFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(outputFile); 
        IOUtils.copy(tis, fos);
        fos.close();
      }
    }
    tis.close();
  }
    
  /**
   * Method to decompress a gzip file
   * @param gZippedFile
   * @param newFile
   * @throws IOException
   */
  private File deCompressGZipFile(File gZippedFile, File tarFile) throws IOException{
    FileInputStream fis = new FileInputStream(gZippedFile);
    GZIPInputStream gZIPInputStream = new GZIPInputStream(fis);
    
    FileOutputStream fos = new FileOutputStream(tarFile);
    byte[] buffer = new byte[1024];
    int len;
    while((len = gZIPInputStream.read(buffer)) > 0){
      fos.write(buffer, 0, len);
    }        
    fos.close();
    gZIPInputStream.close();
    return tarFile;               
  }
    
  /**
   * This method is used to get the tar file name from the gz file
   * by removing the .gz part from the input file
   * @param inputFile
   * @param outputFolder
   * @return
   */
  private static String getFileName(File inputFile, String outputFolder){
    return outputFolder + File.separator + 
      inputFile.getName().substring(0, inputFile.getName().lastIndexOf('.'));
  }
}

That's all for this topic How to Untar a File 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. Creating Tar File And GZipping Multiple Files in Java
  2. Zipping Files And Folders in Java
  3. How to Create Password Protected Zip File in Java
  4. Compressing and Decompressing File in GZIP Format
  5. How to Read File From The Last Line in Java

You may also like-

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. Write to a File in Java
  3. Producer-Consumer Java Program Using volatile
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  6. Interface Default Methods in Java
  7. Lambda Expressions in Java 8
  8. StringBuffer Class in Java With Examples

Java Multithreading Tutorial

This Java multithreading tutorial gives an overview of multithreading in Java, how thread is created and executed, how thread-based multitasking is different from process-based multitasking and how to facilitate inter-thread communication.


Multi-tasking – Thread and Process

Multi-tasking as the name suggests means performing multiple tasks at the same time. Operating systems do support multi-tasking for example you would be coding in Java using your favorite IDE while listening to songs in a player and chatting with your team member to clear some doubts about functionality. So at the same time there are at least 3 processes running IDE, player and a messenger. This is an example of process-based multitasking where more than two programs are running concurrently. In process-based multitasking, a program is the smallest unit of execution.

In thread-based multitasking a single program has two or more threads that can run concurrently. In thread-based multitasking, the thread is the smallest unit of execution. For example in your IDE. Building workspace task is going on in background while you are still writing code because these two tasks are performed by two separate threads.

Multi-threading in Java

Java programming language provides in-built support for multithreaded programming. To create a thread in Java you can use any of the following mechanism-

  1. Creating thread by extending the Thread class
  2. Creating thread by implementing the Runnable interface

Every thread created in Java is an object of Thread class. The code that has to be executed by a thread is provided inside the run method. Whether you implement Runnable interface or extend Thread class you need to override run() method and provide the code.

Thread creation example by implementing Runnable interface

class MyThread implements Runnable{
  @Override
  public void run() {
    System.out.println("In run method of MyThread- " 
      + Thread.currentThread().getName());    
  }    
}

public class ThreadDemo {
  public static void main(String[] args) { 
    System.out.println("In main method- " + Thread.currentThread().getName()); 
    // Passing runnable instance
    Thread thread = new Thread(new MyThread(), "MyThread");
    // Calling start method
    thread.start();
  }
}

Output

In main method- main
In run method of MyThread- MyThread

Thread creation example by extending Thread class

Same example when Thread class is extended. Since MyThread is already of type Thread so start() method is called directly using MyThread instance.

class MyThread extends Thread{
  @Override
  public void run() {
    System.out.println("In run method of MyThread- " 
      + Thread.currentThread().getName());    
  }    
}

public class ThreadDemo {
  public static void main(String[] args) { 
    System.out.println("In main method- " + Thread.currentThread().getName()); 
    // Calling start method
    new MyThread().start();
  }
}

Some of the important points about Java multithreading based on these two examples are as follows-

  • run() method has to be overridden, inside run() method you have to provide the functionality that is executed by the thread.
  • After creating thread instance you need to call start method on that thread. Once the thread is scheduled to start run() method will be implicitly called you don’t need to call run() method yourself. Refer What if run() Method Called Directly Instead of start() Method - Java Multi-Threading to know what happens when run() method is called directly.
  • When a Java program is executed one thread starts running immediately that thread is known as main thread in Java. Other threads are spawned from the main thread.

Types of threads

In Java multithreading there are two types of threads.

  1. User threads- Threads which are created to perform tasks related to the application where these threads are spawned.
  2. Daemon threads- Daemon threads are the thread that run in background to perform some tasks for the program as long as the program is running. Daemon threads in Java are suitable for performing general tasks which are not integral part of the application.

Lifecycle of a thread in Java

Java thread cycle is as follows-

  • New state- When a thread is created either by extending Thread class or implementing Runnable interface it is in "New State".
  • Runnable state- When start() method is called on the thread object, that schedules the thread to begin execution when it gets CPU cycle. This thread state is called Runnable.
  • Blocked state- A thread in the blocked state is waiting to acquire a lock so that it can enter a synchronized block/method.
  • Waiting state- A thread that is waiting indefinitely for another thread to perform a particular action is in the waiting state. A thread goes to waiting state duw to calling one of the following methods.
    • Object.wait with no timeout
    • Thread.join with no timeout
    • LockSupport.park
  • Timed_Waiting- A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. A thread is in the timed waiting state due to calling one of the following methods
    • Thread.sleep
    • Object.wait with timeout
    • Thread.join with timeout
    • LockSupport.parkNanos
    • LockSupport.parkUntil
  • Terminated- A thread that has completed execution is in terminated state.

Refer post Thread States (Thread Life Cycle) in Java Multi-Threading to know more about thread states with examples.

Advantages of Java multi-threading

  1. Multithreading helps you to keep idle time to a minimum as two or more threads are executed concurrently to maximize CPU utilization. With multiple threads one of the thread can execute while another is waiting for some resource.
  2. Thread-based multitasking has less overhead than the process-based multitasking.
  3. Multiple threads share the same address space with in a process saving memory requirement.
  4. Since threads are light weight so context switching from one thread to another is inexpensive.
  5. Since multiple threads are part of the same process so inter-thread communication is also inexpensive.

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Thread Priorities in Java Multi-Threading
  2. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  3. Synchronization in Java - Synchronized Method And Block
  4. Difference Between sleep And wait in Java Multi-Threading
  5. Java ThreadLocal Class With Examples

You may also like-

  1. Difference Between equals() Method And equality Operator == in Java
  2. strictfp in Java
  3. Garbage Collection in Java
  4. CallableStatement Interface in Java-JDBC
  5. Removing Spaces Between Words in a String Java Program
  6. Spring Transaction Management Example - @Transactional Annotation and JDBC
  7. Magic Methods in Python With Examples
  8. Java Multithreading Interview Questions And Answers

Python Program to Find Factorial of a Number

In this post we’ll see how to write a Python program to find factorial of a number.

Factorial of a non-negative integer n is product of all positive integers from 1 to n. For example factorial of 4 can be calculated as-

4! = 4 X 3 X 2 X 1 = 24

Factorial program is one of the first program you'll write to understand recursive function so naturally in this post you'll see python program for factorial using recursion apart from writing using its iterative counterpart.

There is also an inbuilt function in Python for calculating factorial.

1. Recursive program to find factorial. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of factorial program that base case is when num is 1.

def factorial(num):
  # base case(exit recursion)
  if num == 0 or num == 1:
    return 1
  else:
    return num * factorial(num - 1);

num = int(input('Enter a number- '))
print(factorial(num))

Output

Enter a number- 6
720

2. Iterative program to find factorial. Here for loop is used to iterate the passed number until it becomes 1, decrementing by 1 in each pass.

def factorial(num):
  fact = 1
  if num < 0:
    print('Please enter non-negative number')
  else:
    for i in range(num, 1, -1):
      fact = fact * i
    print('Factorial is- ', fact)

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- -4
Please enter non-negative number

Enter a number- 0
Factorial is-  1

Enter a number- 4
Factorial is-  24

3. Using factorial function of the math module in Python. Import math module and use math.factorial() function to find factorial of a number.

import math

def factorial(num):
  print('Factorial is- ', math.factorial(num))

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- 7
Factorial is-  5040

That's all for this topic Python Program to Find Factorial of a Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Fibonacci Series
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Python return Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Class And Object in Python
  3. Removing Spaces From String in Python
  4. Fibonacci Series Program in Java
  5. Buffered Streams in Java IO
  6. DatabaseMetaData Interface in Java-JDBC
  7. Array in Java With Examples
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Thursday, August 25, 2022

Character Streams in Java IO

In this Java IO Stream classes tutorial we’ll go through the Java character stream IO classes.

For Byte stream classes refer this post- Byte Streams in Java IO

Character streams in Java

In Java IO byte stream classes are used when working with bytes or binary objects same way character stream classes are used when when working with characters or Strings. In Java platform character values are stored using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set.

All character stream classes descend from Reader and Writer abstract classes.

Java Reader class

All classes in java.io package for reading character streams descend from Reader class which is an abstract class. List of classes in the hierarchy are as given below-

  • BufferedReader- This reader improves performance by buffering input while reading characters, arrays, and lines.
  • CharArrayReader- This class uses a char array as an input source.
  • LineNumberReader- This class extends BufferedReader and represent a buffered character-input stream that keeps track of line numbers.
  • InputStreamReader- An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. To improve efficiency InputStreamReader should be wrapping within a BufferedReader.
  • FileReader- It is a specialized character stream for reading character files.
  • PushbackReader- A character-stream reader that allows characters to be pushed back into the stream.This allows you to look ahead in the input stream.
  • PipedReader- Piped character-input streams which should be connected to PipedWriter to create a piped stream. Ideally separate threads should be used for PipedReader and PipedWriter.
  • StringReader- A character stream whose source is a string.

Java Writer class

All classes in java.io package for writing character streams descend from Writer class which is an abstract class. List of classes in the hierarchy are as given below-

  • BufferedWriter- Buffers characters while writing text to a character-output stream so as to provide for the efficient writing of single characters, arrays, and strings.
  • CharArrayWriter- This class uses a char array as the destination.
  • OutputStreamWriter- An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. OutputStreamWriter should be wrapped within a BufferedWriter to improve performance.
  • FileWriter- It is a specialized character stream for writing text to character files.
  • PipedWriter- Piped character-input streams which should be connected to PipedReader to create a piped stream. Ideally separate threads should be used for PipedReader and PipedWriter.
  • PrintWriter- Prints formatted representations of objects to a text-output stream.
  • StringWriter- A character stream that collects its output in a string buffer, which can then be used to construct a string.

Java character stream example

In this character stream example line-oriented I/O is used. Lines from a File are read using BufferedReader and written to a file using PrintWriter.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    BufferedReader br = null;
    PrintWriter pw = null;
    try {
      // Streams
      br = new BufferedReader(new FileReader("F:\\Temp\\abc.txt"));
      pw = new PrintWriter(new FileWriter("F:\\Temp\\write.txt"));
      String line;
      while ((line = br.readLine()) != null) {
        pw.println(line);
      }
    } finally {
      // Closing streams
      if (br != null) {
        br.close();
      }
      if (pw != null) {
        pw.close();
      }
    }
  }
}

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  2. Java Program to Convert a File to Byte Array
  3. How to Read Input From Console in Java
  4. How to Read Properties File in Java
  5. Zipping Files And Folders in Java

You may also like-

  1. How to Create PDF From XML Using Apache FOP
  2. PreparedStatement Interface in Java-JDBC
  3. Difference Between ArrayList And CopyOnWriteArrayList in Java
  4. Java Object Cloning - clone() Method
  5. Ternary Operator in Java With Examples
  6. Spring MVC Generate Response as JSON Example
  7. Spring Transaction Management JDBC Example Using @Transactional Annotation
  8. Python String isdigit() Method

Wednesday, August 24, 2022

Difference Between HashMap And ConcurrentHashMap in Java

In this post we'll see the differences between ConcurrentHashMap and HashMap in Java which is also a good Java interview question.

ConcurrentHashMap was added in Java 5 as an alternative to HashTable to improve the performance of the (key, value) pair kind of data structure while still keeping it thread safe. On the other hand HashMap in Java is not synchronized so provides better performance but it is not thread safe.

HashMap Vs ConcurrentHashMap in Java

  1. First and foremost difference between HashMap and ConcurrentHashMap in Java is of course thread safety. ConcurrentHashMap is thread safe and fit for use in a multi-threaded environment whereas HashMap is not thread safe.
  2. Second difference is about how these data structures synchronize. HashMap can be synchronized using the Collections.synchronizedMap() method but that synchronizes all the methods of the HashMap on a common lock and effectively reduces it to a data structure where one thread can enter at a time.

    In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map.

    By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. That means theoretically any given time 16 threads can access ConcurrentHashMap if they all are going to separate buckets.

  3. In ConcurrentHashMap performance is further improved by providing read access concurrently without any blocking. Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).
  4. HashMap allows one null as key but ConcurrentHashMap doesn't allow null as key.

  5. Performace wise HashMap is better as there is no synchronization.

    In case HashMap has to be used in a multi-threaded environment and there is a need to use Collections.SynchronizedMap() method then ConcurrentHashMap() is a better choice as ConcurrentHashMap still gives a chance to more than one thread to access map thus improving performance.

  6. Iterator provided by ConcurrentHashMap is fail-safe which means it will not throw ConcurrentModificationException if the underlying structure is changed during iteration.

    Iterator provided by HashMap is fail-fast as it throws a ConcurrentModificationException if the underlying collection is structurally modified at any time after the iterator is created.

That's all for this topic Difference Between HashMap And ConcurrentHashMap in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ConcurrentHashMap in Java With Examples
  2. Difference Between ArrayList And CopyOnWriteArrayList in Java
  3. Java Semaphore With Examples
  4. Java ReentrantLock With Examples
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. How to Sort HashSet in Java
  3. Lambda Expression Examples in Java
  4. How to Iterate a HashMap of ArrayLists of String in Java
  5. Race Condition in Java Multi-Threading
  6. Interface Default Methods in Java
  7. Java ThreadLocal Class With Examples
  8. How to Read File From The Last Line in Java

Difference Between Two Dates in Java

In this post we’ll see how to calculate difference between two dates in Java in terms of years, months, days, hours, minutes, seconds.

Java 8 onward you can use Period and Duration classes of the new date and time API in Java 8 to find the difference between two dates. Another option is to use SimpleDateFormat class.

Difference between two dates using SimpleDateFormat

Before Java 8 you could calculate difference between two dates manually using SimpleDateFormat.

public class DateDiff {
 public static void main(String[] args) { 
  try {
   dateDifference("28/02/2016 13:15:55", "01/03/2016 17:18:14", "dd/MM/yyyy HH:mm:ss");
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 private static void dateDifference(String date1, String date2, String pattern) throws ParseException{
  SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  Date d1 = sdf.parse(date1);
  Date d2 = sdf.parse(date2);
  long diffInMillis = d2.getTime() - d1.getTime();
  long dateDiffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

  long dateDiffInHours = TimeUnit.HOURS.convert(diffInMillis - (dateDiffInDays * 24 * 60 * 60 * 1000), TimeUnit.MILLISECONDS);

  long dateDiffInMinutes = TimeUnit.MINUTES.convert(diffInMillis - (dateDiffInDays * 24 * 60 * 60 * 1000) -(dateDiffInHours * 60 * 60 * 1000), TimeUnit.MILLISECONDS);

  long dateDiffInSeconds = TimeUnit.SECONDS.convert(diffInMillis - (dateDiffInDays * 24 * 60 * 60 * 1000) - (dateDiffInHours * 60 * 60 * 1000) - (dateDiffInMinutes * 60 * 1000), TimeUnit.MILLISECONDS);

  System.out.println(dateDiffInDays + " day(s) " + dateDiffInHours + " Hour(s) " + dateDiffInMinutes + " Minute(s) " + dateDiffInSeconds + " Second(s)");
 }
}

Output

2 day(s) 4 Hour(s) 2 Minute(s) 19 Second(s)

Difference between two dates in Java 8

Java 8 onward you can use new date and time API classes Period and Duration to find difference between two dates.

  • Period class is used to model amount of time in terms of years, months and days.
  • Duration class is used to model amount of time in terms of seconds and nanoseconds.

Using these two classes you can calculate difference between two dates in terms of years, months, days along with hours, minutes, seconds (for time component).

Difference between dates using Java Period and Duration

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;

public class DateDiff {
 public static void main(String[] args) {
  LocalDateTime dateTime1 = LocalDateTime.of(2016, 8, 28, 13, 15, 55);
  LocalDateTime dateTime2 = LocalDateTime.of(2016, 8, 29, 17, 18, 14);

  getPeriod(dateTime1.toLocalDate(), dateTime2.toLocalDate());
  getTime(dateTime1.toLocalTime(), dateTime2.toLocalTime());
 }
 
 private static void getPeriod(LocalDate date1, LocalDate date2){
  Period p = Period.between(date1, date2);
  System.out.println("Year " + p.getYears());
  System.out.println("Months " + p.getMonths());
  System.out.println("Days " + p.getDays());   
 }

 private static void getTime(LocalTime time1, LocalTime time2){
   
  Duration d = Duration.between(time1, time2);
  long seconds = d.getSeconds();
  //System.out.println("seconds " + seconds);
  // Calculating hours
  System.out.println("Hours " + d.toHours());
  // Calculating Minutes
  System.out.println("Minutes " + ((seconds % 3600)/60));
  // Calculating Seconds
  System.out.println("Seconds " + (seconds % 60));

 }
}

Output

Year 0
Months 0
Days 1
Hours 4
Minutes 2
Seconds 19

Running it with another set of dates-

LocalDateTime dateTime1 = LocalDateTime.of(2016, 8, 28, 13, 15, 55);
LocalDateTime dateTime2 = LocalDateTime.of(2017, 10, 5, 15, 12, 59);

Output

Year 1
Months 1
Days 7
Hours 1
Minutes 57
Seconds 4

That's all for this topic Difference Between Two Dates 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. Compare Dates in Java
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. How to Display Time in AM-PM Format in Java
  4. Format Date in Java Using SimpleDateFormat
  5. How to Convert Date to String in Java

You may also like-

  1. How to Untar a File in Java
  2. How to Create PDF From XML Using Apache FOP
  3. Converting int to string - Java Program
  4. How HashMap Works Internally in Java
  5. Primitive Type Streams in Java Stream API
  6. JVM Run-Time Data Areas - Java Memory Allocation
  7. Serialization and Deserialization in Java
  8. Difference between Encapsulation and Abstraction in Java

Tuesday, August 23, 2022

Unzip File in Java

To unzip files in Java you can use classes provided by java.util.zip package for data compression and decompression.

Steps to unzip file in Java

To unzip a zipped file you need to read data from an input stream. For that you can use ZipInputStream class residing in the java.util.zip package.

Once ZIP input stream is opened, you can read the zip entries using the getNextEntry() method which returns a ZipEntry object. If the end-of-file is reached, getNextEntry returns null.

While going through the zip entries you can check whether that entry is for a directory or for a file, if it is a directory just create the folder in destination. If it is a file then you need to read the data to the output file by opening an OutputStream.

Java program for unzipping file

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Unzip {
  static final int BUFFER = 2048;
  // Output folder
  private static final String DEST_FOLDER = "G://Output";
  public static void main (String argv[]) {
    try {
      File folder = new File(DEST_FOLDER);
      if(!folder.exists()){
        folder.mkdir();
      }
      BufferedOutputStream dest = null;
      // zipped input
      FileInputStream fis = new FileInputStream("G://files.zip");
      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
      ZipEntry entry;
      while((entry = zis.getNextEntry()) != null) {
        System.out.println("Extracting: " +entry);
        int count;
        byte data[] = new byte[BUFFER];
        String fileName = entry.getName();
        File newFile = new File(folder + File.separator + fileName);
        // If directory then just create the directory (and parents if required)
        if(entry.isDirectory()){
          if(!newFile.exists()){
            newFile.mkdirs();
          }
        }else{                
          // write the files to the disk
          FileOutputStream fos = new FileOutputStream(newFile);
          dest = new BufferedOutputStream(fos, BUFFER);
          while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
          }
          dest.flush();
          dest.close();
        }
        zis.closeEntry();                
      }
      zis.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

Note that though here output folder is taken as a separate folder with different name, but you can also derive that name using the input folder name.

That's all for this topic Unzip File 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. How to Untar a File in Java
  2. How to Find Last Modified Date of a File in Java
  3. How to Read File From The Last Line in Java
  4. Reading File in Java Using BufferedReader
  5. Reading File in Java Using Scanner

You may also like-

  1. How to Sort ArrayList of Custom Objects in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Deadlock in Java Multi-Threading
  4. final Vs finally Vs finalize in Java
  5. Creating Custom Exception Class in Java
  6. Java Abstract Class and Abstract Method
  7. Callable and Future in Java With Examples
  8. Executor And ExecutorService in Java With Examples

Monday, August 22, 2022

getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java

While using Java IO if you ever tried to get path of the file using methods of the File class you would have seen three methods getPath(), getAbsolutePath() and getCanonicalPath() for getting the path of the file. If you ever wondered why these three methods and what are the differences among these three methods getPath(), getAbsolutePath() and getCanonicalPath() in Java then this article tries to explain these methods and the differences.


File path – Absolute and Relative

User interfaces and operating systems use system-dependent pathname strings to name files and directories. File class in Java presents an abstract, system-independent view of hierarchical pathnames.

When an abstract pathname is converted into a pathname string it is inherently system-dependent, each name is separated from the next by a single separator character which is "/" for Unix and "\" for Windows.

File pathname, whether abstract or in string form, may be either absolute or relative.

An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. For example– C:\Users\netjs\Test.txt

Using absolute pathname in a program or script is like hardcoding the file name which requires file to be always present in the given pathname.

A relative pathname is resolved against some other pathname (current user directory). Using relative pathname in a program or script is consider better option as path is resolved as per the location from where the program or script is executed.

getPath() method in File class

This method converts abstract pathname into a pathname string. If the File object is created using a relative path then the path returned is a relative path, if it’s created using an absolute path then the path returned is an absolute path.

The resulting string uses the separator character to separate the names in the name sequence. On UNIX systems the value of this separator field is '/'; on Microsoft Windows systems it is '\\'.

// absolute path
File file = new File("F://Temp/abc.txt");
System.out.println(file.getPath());

Output

F:\Temp\abc.txt

You can see absolute path is returned as the object is created using an absolute path. Also separator is changed for Windows system as the separator character is system dependent.

// relative path
File file = new File("Temp\\abc.txt");
System.out.println(file.getPath());

Output

Temp\abc.txt

You can see relative path is returned as the object is created using relative path.

Same example in Linux system-

// relative path
File file = new File("Temp/abc.txt");
System.out.println("Path- " + file.getPath());
System.out.println("Absolute Path- " + file.getAbsolutePath());

Output

Path- Temp/abc.txt
Absolute Path- /home/netjs/java-workspace/Temp/abc.txt

getAbsolutePath() method in Java File class

This method returns the absolute pathname string of the abstract file pathname. If this abstract pathname is already absolute, then the same pathname string is returned. Otherwise this pathname is resolved in a system-dependent way. On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.

public class FilePath {
 public static void main(String[] args) {
  // relative path
  File file = new File("Temp\\abc.txt");
  System.out.println(file.getAbsolutePath());
 }
}

Output

F:\Anshu\NetJs\NetJS\Temp\abc.txt

In the example relative pathname is passed while creating file object which is resolved to the current user directory.

Note that there may be more than one absolute path pointing to the same file. For examples following absolute paths are for the same path (F:\Temp\abc.txt)-

F:\Temp\abc.txt

F:\\Temp\\..\\Temp\\abc.txt

F:\\Temp\\.\\abc.txt

Here ../ refers parent directory where as ./ refers current directory.

In case of getAbsolutePath() method redundant names such as "." and ".." are not resolved.

getCanonicalPath() method in Java File class

This method returns the canonical pathname string of this abstract pathname. A canonical pathname is both absolute and unique. This method converts the pathname to absolute form same as done by getAbsolutePath() method. How getCanonicalPath() differs from getAbsolutePath() is that this method removes redundant names such as "." and ".." from the pathname, resolves symbolic links (on UNIX platforms) and converts drive letters to a standard case (on Microsoft Windows platforms).

File file = new File("F:\\Temp\\abc.txt");
System.out.println("Absolute path- " + file.getAbsolutePath());
try {
 System.out.println("Canonical path- " + file.getCanonicalPath());
} catch (IOException e) {
 e.printStackTrace();
}

Output

Absolute path- F:\Temp\abc.txt
Canonical path- F:\Temp\abc.txt

In this case both absolute path and canonical paths are same.

File file = new File("f:\\Temp\\..\\Temp\\abc.txt");
System.out.println("Absolute path- " + file.getAbsolutePath());
try {
 System.out.println("Canonical path- " + file.getCanonicalPath());
} catch (IOException e) {
 e.printStackTrace();
}

Output

Absolute path- f:\Temp\..\Temp\abc.txt
Canonical path- F:\Temp\abc.txt

In this code you can see the difference between the getAbsolutePath() and getCanonicalPath() methods. As shown in the output getCanonicalPath() method removed "." and ".." from the pathname also drive letter is converted to a standard case (in Windows).

File file = new File("F:\\Temp\\.\\abc.txt");
System.out.println("Absolute path- " + file.getAbsolutePath());
try {
 System.out.println("Canonical path- " + file.getCanonicalPath());
} catch (IOException e) {
 e.printStackTrace();
}

Output

Absolute path- F:\Temp\.\abc.txt
Canonical path- F:\Temp\abc.txt

Again you can see that though absolute path can be written in many different ways for the same path but canonical path is unique.

File path example in Linux system-

File file = new File("/home/netjs/java-workspace/./Temp/abc.txt");
System.out.println("Absolute Path- " + file.getAbsolutePath());
try {
 System.out.println("Canonical Path- " + file.getCanonicalPath());
} catch (IOException e) {

 e.printStackTrace();
}

Output

Absolute Path- /home/netjs/java-workspace/./Temp/abc.txt
Canonical Path- /home/netjs/java-workspace/Temp/abc.txt

That's all for this topic getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Write to a File in Java
  2. Read or List All Files in a Folder in Java
  3. How to Find Last Modified Date of a File in Java
  4. Reading File in Java Using Files.lines And Files.newBufferedReader
  5. How to Write Excel File in Java Using Apache POI

You may also like-

  1. Java Variable Types With Examples
  2. java.lang.ClassCastException - Resolving ClassCastException in Java
  3. How to Loop Through HashSet in Java
  4. Thread Priorities in Java Multi-Threading
  5. Serialization Proxy Pattern in Java
  6. Java Concurrency Interview Questions And Answers
  7. Spring JdbcTemplate With ResultSetExtractor Example
  8. Spring Integration With Quartz Scheduler