Find start node of loop in linkedlist in java

In this post, we will see how to find start node of loop in linkedlist in java. We have already seen how to detect a loop in linkedlist in java. This is extension of that post.

Algorithm:

It is quite easy to find starting node of loop in linkedlist.
  • Find meeting point of slowPointer and fastPointer.
  • set slowPointer to head node of linkedlist.
  • Move slowPointer and fastPointer both by one node.
  • The node at which slowPointer and fastPointer meets, will be starting node of loop.
public Node  findStartNodeOfTheLoop() {
  Node fastPtr = head;
  Node slowPtr = head;
  boolean loopExists=false;
  while (fastPtr != null && fastPtr.next != null) {
   fastPtr = fastPtr.next.next;
   slowPtr = slowPtr.next;
   if (slowPtr == fastPtr)
   {
    loopExists=true;
    break;
   }

  }
  if(loopExists)
  {
   slowPtr=head;

   while(slowPtr!=fastPtr)
   {
    slowPtr=slowPtr.next;
    fastPtr=fastPtr.next;
   }

   
  }
  else
  {
   System.out.println("Loop does not exists");
   slowPtr=null;
  }
  return slowPtr;
 }

You must be wondering how above approach will work.

Lets understand with help of example:

As per above diagram:


Distance travelled by slowPointer= A+B
Distance travelled by fastPointer= (A+B+C) + B =A+2B+C

Let speed of slow pointer be X , so speed of fast pointer will be 2*X
As per simple distance speed, time relation:

(A+B)/X=A+2B+C/2*X

2*(A+B)=A+2B+C

2A+2B=A+2B+C

A=C

Hence if we set slowPointer to head and move both slowPointer and fastpointer by one node, they will meet at start node of loop.

Java code :

package org.arpit.java2blog;

public class LinkedList{

 private Node head;

 private static class Node {
  private int value;
  private Node next;

  Node(int value) {
   this.value = value;

  }
 }

 public void addToTheLast(Node node) {

  if (head == null) {
   head = node;
  } else {
   Node temp = head;
   while (temp.next != null)
    temp = temp.next;

   temp.next = node;
  }
 }


 public void printList() {
  Node temp = head;
  while (temp != null) {
   System.out.format("%d ", temp.value);
   temp = temp.next;
  }
  System.out.println();
 }

 public Node  findStartNodeOfTheLoop() {
  Node fastPtr = head;
  Node slowPtr = head;
  boolean loopExists=false;
  while (fastPtr != null && fastPtr.next != null) {
   fastPtr = fastPtr.next.next;
   slowPtr = slowPtr.next;
   if (slowPtr == fastPtr)
   {
    loopExists=true;
    break;
   }

  }
  if(loopExists)
  {
   slowPtr=head;

   while(slowPtr!=fastPtr)
   {
    slowPtr=slowPtr.next;
    fastPtr=fastPtr.next;
   }

   
  }
  else
  {
   System.out.println("Loop does not exists");
   slowPtr=null;
  }
  return slowPtr;
 }


 public static void main(String[] args) {
  LinkedList list = new LinkedList();
  // Creating a linked list
  Node loopNode=new Node(7);
  list.addToTheLast(new Node(5));
  list.addToTheLast(new Node(6));
  list.addToTheLast(loopNode);
  list.addToTheLast(new Node(1));
  list.addToTheLast(new Node(2));

  list.printList();
  list.addToTheLast(loopNode);  

  Node startNode=list.findStartNodeOfTheLoop();
  if(startNode!=null)
   System.out.println("start Node of loop is "+ startNode.value);



 }
}

When you run above program, you will get following output:
5 6 7 1 2 
start Node of loop is 7



How to make a file read only in java

In this post, we will see how to make a read only file in java. It is very simple. You need to just call java.io.File 's  setReadOnly() method.

1) How to make a file read only

Java program:

package org.arpit.java2blog;

import java.io.File;

public class FileHiddenMain {

 public static void main(String[] args) {
  System.out.println("-----------------");
  // Read the file
  File configFile=new File("/Users/Arpit/Desktop/config.properties");
  configFile.setReadOnly();
  
  if(configFile.canWrite())
  {
   System.out.println("Config file can be writtern");
  }
  else
  {
   System.out.println("config file is read only");
  }

  System.out.println("-----------------");

            }
     }
When you run above program, you will get following output:
-----------------
config file is read only
-----------------

2) How to make it writable  again

If you have made file read only, you can make file writable again by using method setWritable(true).
This method is introduced in java 1.6.

Java program:

package org.arpit.java2blog;

import java.io.File;

public class FileHiddenMain {

 public static void main(String[] args) {
  System.out.println("-----------------");
  // Read the file
  File configFile=new File("/Users/Arpit/Desktop/config.properties");
  configFile.setReadOnly();
  
  if(configFile.canWrite())
  {
   System.out.println("Config file can be written");
  }
  else
  {
   System.out.println("config file is read only");
  }

  System.out.println("-----------------");

  System.out.println("Making config file writable again");
  // this method is available from jdk 1.6
  configFile.setWritable(true);
  
  if(configFile.canWrite())
  {
   System.out.println("Config file can be written");
  }
  else
  {
   System.out.println("config file is read only");
  }

  System.out.println("-----------------");
 }

}





When you run above program, you will get following output:
-----------------
config file is read only
-----------------
Making config file writable again
Config file can be written
-----------------





How to import all classes at once in eclipse

In this post, we will see how to import all classes at once in eclipse.

Problem : 

Sometimes you copy any java code from somewhere and you see many import errors. You go to each class and press ctrl + space to import each class one by one. Lets say you have large number of classes, you have to import each class one by one.

Solution:

Eclipse have provided organize imports feature which can import all classes at once and prompt you to select any class if there are multiple classes of same name present in classpath.
Right click -> source -> organize imports

Shortcut:

ctrl + shift + o

Lets understand with the help of example:




You can see, we need to import lot of classes. Just press ctrl + shift + o, you will see below screen.



Bingo!! you have resolved all import errors at once. I use this shortcut very often, I hope you find it useful.





Read a file from resources folder in java

In this post, we will see how to read a file from resources folder in java. If you create a maven project(simple java or dynamic web project) , you will see folder src/java/resources. You can read from resources folder using these simple code.

 
                        // Getting ClassLoader obj
   ClassLoader classLoader = this.getClass().getClassLoader();
   // Getting resource(File) from class loader
   File configFile=new File(classLoader.getResource(fileName).getFile());

Project structure:

Java Program:

package org.arpit.java2blog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
/*
 * @author Arpit Mandliya
 */
public class ReadPropertiesFileJavaMain {

 public static void main(String args[]) throws IOException
 {
  ReadPropertiesFileJavaMain rp=new ReadPropertiesFileJavaMain();
  System.out.println("Reading file from resources folder");
  System.out.println("-----------------------------");

  rp.readFile("config.txt");
  
  System.out.println("-----------------------------");
 }

 public  void readFile(String fileName) throws IOException
 {
  FileInputStream inputStream=null;
  
  try {
   // Getting ClassLoader obj
   ClassLoader classLoader = this.getClass().getClassLoader();
   // Getting resource(File) from class loader
   File configFile=new File(classLoader.getResource(fileName).getFile());
  
   inputStream = new FileInputStream(configFile);
   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
   String line;
   while ((line = reader.readLine()) != null) {
   System.out.println(line);
   }
 
   reader.close();


  } catch (FileNotFoundException e) {

   e.printStackTrace();
  }catch (IOException e) {

   e.printStackTrace();
  }
  finally {
   inputStream.close();
  }

  
 }

}

When you run above program, you will get following output.
Reading file from resources folder
-----------------------------
host = localhost
username = java2blog
password = java123
-----------------------------

How to read properties file in java

Properties files are used in java projects to externalise configuration, for example, database settings. In this post , we will see how to read properties file in java.

Java used Properties class to store above key values pair. Properties.load method is very convenient to load properties file in form of key values pairs.

Properties file looks something like this.



There are two ways you can do it.
  • Read properties file from system
  • Read properties file  from classpath

Read properties file from System :

In this, you need to read properties file from system path. Here I am putting properties file in root level of project.


java code:
package org.arpit.java2blog;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/*
 * @author Arpit Mandliya
 */
public class ReadPropertiesFileJavaMain {

 public static void main(String args[]) throws IOException
 {
  System.out.println("Reading from properties file");
  System.out.println("-----------------------------");
  Properties prop=readPropertiesFile("config.properties");
  
  System.out.println("host : "+prop.getProperty("host"));
  System.out.println("username : "+prop.getProperty("username"));
  System.out.println("password : "+prop.getProperty("password"));
  System.out.println("-----------------------------");
 }

 public static Properties readPropertiesFile(String fileName) throws IOException
 {
  FileInputStream fis=null;
  Properties prop=null;
  try {
   fis= new FileInputStream(fileName);
   // create Properties class object
   prop=new Properties();
   // load properties file into it
   prop.load(fis);

  } catch (FileNotFoundException e) {

   e.printStackTrace();
  }catch (IOException e) {

   e.printStackTrace();
  }
  finally {
   fis.close();
  }

  return prop;
 }

}

When you run above program, you will get following output:
Reading from properties file
-----------------------------
host : localhost
username : java2blog
password : java123
-----------------------------

Read properties file from classpath: 

You can read properties file to classpath too. you have $project/src as default classpath as this src folder will be copied to classes. You can put it in $project/src folder and read it from there.


 you need to use
this.getClass().getResourceAsStream("/config.properties");
to read it from classpath.
package org.arpit.java2blog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/*
 * @author Arpit Mandliya
 */
public class ReadPropertiesFileJavaMain {

 public static void main(String args[]) throws IOException
 {
  ReadPropertiesFileJavaMain rp=new ReadPropertiesFileJavaMain();
  System.out.println("Reading from properties file");
  System.out.println("-----------------------------");
  
  Properties prop=rp.readPropertiesFile("/config.properties");

  System.out.println("host : "+prop.getProperty("host"));
  System.out.println("username : "+prop.getProperty("username"));
  System.out.println("password : "+prop.getProperty("password"));
  System.out.println("-----------------------------");
 }

 public  Properties readPropertiesFile(String fileName) throws IOException
 {
  InputStream fis=null;
  Properties prop=null;
  try {
   prop=new Properties();
   fis=this.getClass().getResourceAsStream(fileName);
  
   // create Properties class object
   if (fis != null) {
    // load properties file into it
    prop.load(fis);
   } else {
    throw new FileNotFoundException("property file '" + fileName + "' not found in the classpath");
   }

  } catch (FileNotFoundException e) {

   e.printStackTrace();
  }catch (IOException e) {

   e.printStackTrace();
  }
  finally {
   fis.close();
  }

  return prop;
 }

}

When you run above program, you will get following output:
Reading from properties file
-----------------------------
host : localhost
username : java2blog
password : java123
-----------------------------

How to read object from a file in java

In this post, we will see how to read object from file in java. In last post, we have already seen how to write object to a file and created employee.ser , now in this post, we are going to read same file and retrieve back Employee object.

Reading object from file using ObjectInputStream may be referred as Deserialization.

Steos for reading object from file are:

Lets take an example:
Create Employee.java same as last example in src->org.arpit.java2blog

1.Employee.java
package org.arpit.java2blog;
import java.io.Serializable;
public class Employee implements Serializable{ 
   private static final long serialVersionUID = 1L;    
  int employeeId;
    String employeeName;
    String department;
    
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
}

Create DeserializeMain.java in src->org.arpit.java2blog

2.DeserializeMain.java
package org.arpit.java2blog;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeMain {
 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
  
  Employee emp = null;
       try
       {
          FileInputStream fileIn =new FileInputStream("employee.ser");
          ObjectInputStream in = new ObjectInputStream(fileIn);
          emp = (Employee) in.readObject();
          in.close();
          fileIn.close();
       }catch(IOException i)
       {
          i.printStackTrace();
          return;
       }catch(ClassNotFoundException c)
       {
          System.out.println("Employee class not found");
          c.printStackTrace();
          return;
       }
       System.out.println("Deserialized Employee...");
       System.out.println("Emp id: " + emp.getEmployeeId());
       System.out.println("Name: " + emp.getEmployeeName());
       System.out.println("Department: " + emp.getDepartment());
 }
}

3.Run it:

When you run above DeserializeMain.java and you will get following output:
Deserialized Employee...
Emp id: 101
Name: Arpit
Department: CS

These are some simple steps to read object from file. If you want to go through some complex scenario you can go through Serialization in java

How to write object to a file in java

If you want to send object over network, then you need to  write object to a file and convert it to the stream. This process can be referred as serialization.

Object needs to implement Serializable interface which is marker interface  interface and we will use java.io.ObjectOutputStream to write object to a file.

Lets go through steps for writing object to a file.


Lets take an example:
Create Employee.java in src->org.arpit.java2blog

1.Employee.java
package org.arpit.java2blog;
import java.io.Serializable;
public class Employee implements Serializable{ 
   private static final long serialVersionUID = 1L;    
  int employeeId;
    String employeeName;
    String department;
    
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
}
As you can see above,if you want to serialize any class then it must implement Serializable interface which is marker interface.
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface
Create SerializeMain.java in src->org.arpit.java2blog

2.SerializeMain.java
package org.arpit.java2blog;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
 public class SerializeMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  Employee emp = new Employee();
  emp.setEmployeeId(101);
  emp.setEmployeeName("Arpit");
  emp.setDepartment("CS");
  try
  {
   FileOutputStream fileOut = new FileOutputStream("employee.ser");
   ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
   outStream.writeObject(emp);
   outStream.close();
   fileOut.close();
  }catch(IOException i)
  {
   i.printStackTrace();
  }
 }
}
When you run above program,employee.ser will get created. Its content won't be in human readable format but it will have object stored on file . You can use ObjectInputStream to read same object from file.

These are some simple steps to write object to a file. If you want to go through some complex scenario you can go through Serialization in java

How to get last modified date of file in java

In this post, we will see how to get last modified date of file in java. We can use java.io.File's lastModified() method to get last modified date. This function returns time in milliseconds(long). We can convert this to required date format using SimpleDateFormat.

Java Program: 

package org.arpit.java2blog;

import java.io.File;
import java.text.SimpleDateFormat;

public class GetLastModifiedTimeOfFileMain {

	public static void main(String[] args)
	{
		System.out.println("-----------------");
		// Read the file
		File mp3File=new File("/Users/Arpit/Desktop/MySong.mp3");
		
		System.out.println("Time inmilliseconds: "+mp3File.lastModified());
		
		SimpleDateFormat sdf= new SimpleDateFormat("dd MMM yyyy HH:mm:sss");
		
		String dateFormat=sdf.format(mp3File.lastModified());
		
		System.out.println("Time in date format: "+dateFormat);
		
		System.out.println("-----------------");
		
		
		
	}
}

When you run above program, you will get below output:
-----------------
Time in milliseconds: 1424326757000
Time in date format: 19 Feb 2015 11:49:017
-----------------


How to get all files with certain extension in a folder in java

In this post, we will see how to list all files with certain extension in a folder.
For example, you want to list all .jpg or .zip files in a folder.

We will  use FilenameFilter interface to list the files in a folder, so we will create a inner class which will implement FilenameFilter interface and implement accept method. We need to pass created inner class to java.io.File 's list method to list all files with specific extension.

Java Program :
package org.arpit.java2blog;

import java.io.File;
import java.io.FilenameFilter;

public class GetAllFilesWithCertainExtMain {
 /*
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  GetAllFilesWithCertainExtMain main=new GetAllFilesWithCertainExtMain();
  System.out.println("Finding .zip files in the folder /Users/Arpit/Desktop/Blog");
  System.out.println("-----------------");
  // Read the file
  File folder=new File("/Users/Arpit/Desktop/Blog");
  main.getAllFilesWithCertainExtension(folder,"zip");
  
  System.out.println("-----------------");
 }
 
 public  void getAllFilesWithCertainExtension(File folder,String filterExt)
 {
  MyExtFilter extFilter=new MyExtFilter(filterExt);
  if(!folder.isDirectory())
  {
   System.out.println("Not a folder");
  }
  else
  {
   // list out all the file name and filter by the extension
   String[] list = folder.list(extFilter);

   if (list.length == 0) {
    System.out.println("no files end with : " + filterExt);
    return;
   }

   for (int i = 0; i < list.length; i++) {
    System.out.println("File :"+list[i]);
   }
  }
 }
 
 // inner class, generic extension filter
  public class MyExtFilter implements FilenameFilter {

   private String ext;

   public MyExtFilter(String ext) {
    this.ext = ext;
   }

   public boolean accept(File dir, String name) {
    return (name.endsWith(ext));
   }
  }
}

When I ran above program, I got following output:
Finding .zip files in the folder /Users/Arpit/Desktop/Blog
-----------------
File :sampleFile1.zip
File :sampleFile2.zip
File :sampleFile3.zip
File :Spring3-Quartz-Example.zip
File :SpringQuartzIntegrationExample.zip
-----------------

So we have found all .zip file in folder "/Users/Arpit/Desktop/Blog"

How to delete non empty directory in java

In this post, we will see how to delete Directory/Folder which is non empty. You can use java.io.File 's delete empy folder but you can not delete it if it is non empty.
There are multiple ways to do it.
  • Using java recursion
  • Using Apache common IO

Using java recursion:

It is very straight forward to do it. It will iterate through all files in the folder. If it is a file then we can directly delete it but if It finds folder inside it then we again call same method.
// Delete using recursion
 public static void delete(File file)
   throws IOException{

  if(file.isDirectory()){

   //We can directly delete if we found empty directory
   if(file.list().length==0){

    file.delete();
    System.out.println("Deleting folder : " 
      + file.getAbsolutePath());

   }else{

    //list all the files in directory
    File files[] = file.listFiles();

    for (File temp : files) {
     //recursive delete
     delete(temp);
    }

    // Check directory again, if we find it empty, delete it
    if(file.list().length==0){
     file.delete();
     System.out.println("Deleting folder : " 
       + file.getAbsolutePath());
    }
   }

  }else{
   //if file, then we can directly delete it
   file.delete();
   System.out.println("Deleting file  : " + file.getAbsolutePath());
  }
 }


Using Apache common IO:

Delete non empty folder is very straight forward. You just need to call FileUtils.deleteDirectory() method.
// Delete using Apache common IO
 public static void deleteUsingApacheIO(File f)
 {
  try {
   FileUtils.deleteDirectory(f);
  } catch (IOException e) {

   e.printStackTrace();
  }
 }

Java Program:

package org.arpit.java2blog;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class DeleteNonEmptyDirectoryMain {

 public static void main(String[] args) {
  
  
  System.out.println("Deleting using recursion");
  System.out.println("---------------");
  File folder= new File("/Users/Arpit/Desktop/Blog/temp1");
  // Using recusrion
  try {
   delete(folder);
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  System.out.println("---------------");
  System.out.println("Deleting using Apache IO");
  File folder2= new File("/Users/Arpit/Desktop/Blog/temp2");
  deleteUsingApacheIO(folder2);
  System.out.println("Deleting folder : " 
    + folder2.getAbsolutePath());
 }

 // Delete using recursion
 public static void delete(File file)
   throws IOException{

  if(file.isDirectory()){

   //We can directly delete if we found empty directory
   if(file.list().length==0){

    file.delete();
    System.out.println("Deleting folder : " 
      + file.getAbsolutePath());

   }else{

    //list all the files in directory
    File files[] = file.listFiles();

    for (File temp : files) {
     //recursive delete
     delete(temp);
    }

    // Check directory again, if we find it empty, delete it
    if(file.list().length==0){
     file.delete();
     System.out.println("Deleting folder : " 
       + file.getAbsolutePath());
    }
   }

  }else{
   //if file, then we can directly delete it
   file.delete();
   System.out.println("Deleting file  : " + file.getAbsolutePath());
  }
 }

 // Delete using Apache common IO
 public static void deleteUsingApacheIO(File f)
 {
  try {
   FileUtils.deleteDirectory(f);
  } catch (IOException e) {

   e.printStackTrace();
  }
 }
}

When I ran above program, I got following output
Deleting using recursion
---------------
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/.DS_Store
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/BinaryTree/.DS_Store
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/BinaryTree/verticalSum.jpg.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/BinaryTree/VerticalSumOrder.png
Deleting folder : /Users/Arpit/Desktop/Blog/temp1/BinaryTree
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/.DS_Store
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyJsonCountry.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyJsonCountryID.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyMavenBuild.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyMavenCleanInstall.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyProjectStructure.png
Deleting folder : /Users/Arpit/Desktop/Blog/temp1/jersey json
Deleting folder : /Users/Arpit/Desktop/Blog/temp1
---------------
Deleting using Apache IO
Deleting folder : /Users/Arpit/Desktop/Blog/temp2



How to download file from URL in java

In this post, we will see how to download file from URL in java. It can be used when you want to automatically download any file from URL using java.

There are many ways to do it and some of them are :

Java Program:

package org.arpit.java2blog;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import org.apache.commons.io.FileUtils;

/*
 * @author Arpit Mandliya
 */
public class FileDownloadFromURLMain {

 public static void main(String[] args) {


  String dirName = "/Users/Arpit/Desktop/Blog";

  try {

   System.out.println("---------------------------");
   System.out.println("Downloading file from github using java file IO");
   
   // Using java IO
   downloadFileFromUrlWithJavaIO(
     dirName + "/sampleFile1.zip",
     "https://github.com/arpitmandliya/SpringRestfulWebServicesWithJSONExample/archive/master.zip");

   System.out.println("Downloaded file from github using java file IO");
   System.out.println("---------------------------");
   System.out.println("Downloading file from github using apache common IO");

   // Using Apache common IO
   downloadFileFromUrlWithCommonsIO(
     dirName + "/sampleFile2.zip",
     "https://github.com/arpitmandliya/SpringSecurityHelloWorldExample/archive/master.zip");

   System.out.println("Downloaded file from github using apache common IO");
   System.out.println("---------------------------");
   System.out.println("Downloading file from github using NIO");

   // Using NIO
   downloadFileFromURLUsingNIO(
     dirName + "/sampleFile3.zip",
     "https://github.com/arpitmandliya/SpringMVCHelloWorldExample/archive/master.zip");

   System.out.println("Downloaded file from github using NIO");
   System.out.println("---------------------------");

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 // Using Java IO
 public static void downloadFileFromUrlWithJavaIO(String fileName, String fileUrl)
   throws MalformedURLException, IOException {
  BufferedInputStream inStream = null;
  FileOutputStream outStream = null;
  try {
   URL fileUrlObj=new URL(fileUrl);
   inStream = new BufferedInputStream(fileUrlObj.openStream());
   outStream = new FileOutputStream(fileName);

   byte data[] = new byte[1024];
   int count;
   while ((count = inStream.read(data, 0, 1024)) != -1) {
    outStream.write(data, 0, count);
   }
  } finally {
   if (inStream != null)
    inStream.close();
   if (outStream != null)
    outStream.close();
  }
 }

 // Using common IO
 public static void downloadFileFromUrlWithCommonsIO(String fileName,
   String fileUrl) throws MalformedURLException, IOException {
  FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
 }

 // Using NIO
 private static void downloadFileFromURLUsingNIO(String fileName,String fileUrl) throws IOException {
  URL url = new URL(fileUrl);
  ReadableByteChannel rbc = Channels.newChannel(url.openStream());
  FileOutputStream fOutStream = new FileOutputStream(fileName);
  fOutStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
  fOutStream.close();
  rbc.close();
 }

}
When you run above program , file will be downloaded in above mentioned directory.You will get following output:
---------------------------
Downloading file from github using java file IO
Downloaded file from github using java file IO
---------------------------
Downloading file from github using apache common IO
Downloaded file from github using apache common IO
---------------------------
Downloading file from github using NIO
Downloaded file from github using NIO
---------------------------



How to check if a file exists in Java

It is very easy to check if file exists or not in your file system. You can use java.io.File's exists() method to check if file exists or not.

Java program :

package org.arpit.java2blog;

import java.io.File;

public class FileExistsMain {
 /*
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  System.out.println("-----------------");
  // Read the file
  File mp3File=new File("/Users/Arpit/Desktop/MySong.mp3");
  
  if(mp3File.exists())
  {
   System.out.println("MySong.mp3 file exists");
  }
  else
  {
   System.out.println("MySong.mp3 file does not exist");
  }
  
  System.out.println("-----------------");
  
  File mp3FileFolder=new File("/Users/Arpit/Desktop/MySong");
  
  if(mp3FileFolder.exists())
  {
   System.out.println("MySong folder exists");
  }
  else
  {
   System.out.println("MySong folder does not exist");
  }
  System.out.println("-----------------");
 }

}

When you run above program, you will get following output:
-----------------
MySong.mp3 file exists
-----------------
MySong folder does not exist
-----------------

How to get extension of file in java

In this post, we will see how to get extension of file in java. As java.io.File does not provide any direct method for getting extension of file. This is used when you want to process file differently on the basis of its extension. I have worked on a project where I required this utility method.

There are two simple way to get it.
  • using simple String handling program
  • using Apache io

Using simple String handling program:

Create a simple java class named "GetExtensionOfFileMain.java"
package org.arpit.java2blog;

import java.io.File;

public class GetExtensionOfFileMain {

	public static void main(String[] args)
	{
		ClassLoader classLoader = GetExtensionOfFileMain.class.getClassLoader();
		
		File xlsxFile=new File(classLoader.getResource("Countries.xlsx").getFile());
		String fileExtension=getExtensionOfFile(xlsxFile);
		System.out.println("File extension for Countries.xlsx is "+ fileExtension);
		
		File csvFile=new File(classLoader.getResource("Capital.csv").getFile());;
		String fileExtensionCSV=getExtensionOfFile(csvFile);
		System.out.println("File extension for Captial.csv is "+fileExtensionCSV);
		
		File folder=new File("src/main/resources");
		String fileExtensionFolder=getExtensionOfFile(folder);
		System.out.println("File extension for src/main/resources is "+fileExtensionFolder);
	}
	
	public static String getExtensionOfFile(File file)
	{
		String fileExtension="";
		// Get file Name first
		String fileName=file.getName();
		
		// If fileName do not contain "." or starts with "." then it is not a valid file
		if(fileName.contains(".") && fileName.lastIndexOf(".")!= 0)
		{
			fileExtension=fileName.substring(fileName.lastIndexOf(".")+1);
		}
		
		return fileExtension;
	}
}

When you run above program, you will get following output:
File extension for Countries.xlsx is xlsx
File extension for Captial.csv is csv
File extension for src/main/resources is 

Using Apache io:

You need to download Apcahe io jar and put it to the classpath.
After doing above steps, you just need to call FilenameUtils.getExtension to retrieve file name

package org.arpit.java2blog;

import java.io.File;

import org.apache.commons.io.FilenameUtils;

public class GetFileExtensionApache {

	public static void main(String[] args)
	{
		ClassLoader classLoader = GetFileExtensionApache.class.getClassLoader();
		
		File xlsxFile=new File(classLoader.getResource("Countries.xlsx").getFile());
		String fileExtension=FilenameUtils.getExtension(xlsxFile.getName());
		System.out.println("File extension for Countries.xlsx is "+ fileExtension);
		
		File csvFile=new File(classLoader.getResource("Capital.csv").getFile());;
		String fileExtensionCSV=FilenameUtils.getExtension(csvFile.getName());
		System.out.println("File extension for Captial.csv is "+fileExtensionCSV);
		
		File folder=new File("src/main/resources");
		String fileExtensionFolder=FilenameUtils.getExtension(folder.getName());
		System.out.println("File extension for src/main/resources is "+fileExtensionFolder);
	}
	
	
}

When you run above program, you will get foloowing output:
File extension for Countries.xlsx is xlsx
File extension for Captial.csv is csv
File extension for src/main/resources is