Java Program to detect USB Device

Hey Everyone! In this article, we will learn how to detect a USB device in Java that is inserted into a PC/laptop.


We know that the external USB inserted into the PC/laptop is detected by the computer and is given the drive name as E,F,G,H and so on.
Hence we know that the drives with names E,G,H,F are external USB devices that are inserted into the machine.

Refer the following code below:


Java Program to Detect USB device

package usbdetection;

import java.io.File;

public class UsbDetection {

   
    public static void main(String[] args) {
        
      //here the usb drive names are named as E,F,G,H in the system
      String[] drive_name = new String[]{ "E", "F", "G", "H", "I" ,"J","K", "L","M", "N"};
      //here we initialize an array for the usb that is to be inserted
      File[] usb = new File[drive_name.length];
      //if the usb is detected then it is assigned True else False
      boolean[] usb_detected = new boolean[drive_name.length];
 
      // in below loop we append :/ to the drive names because E:/ D:/  
      //and then the corresponding drive is searched with the help of canRead() method
       
 
    for ( int i = 0; i < drive_name.length; ++i )
    {
         usb[i] = new File(drive_name[i]+":/");
         //This method determines whether the program can read the file denoted by the mentioned path name
         usb_detected[i] = usb[i].canRead();
    }
 
System.out.println("Insert USB");

detect(usb,drive_name,usb_detected);


  }
    
    
    
    public static void detect(File[] usb,String[] drive_name,boolean[] usb_detected)
    {
        while(true)
    {
        //the following loop is iterated to find the usb inserted
        for ( int i = 0; i < drive_name.length; ++i )
        {
            boolean if_detected;
            if_detected = usb[i].canRead();

            if ( if_detected != usb_detected[i] )
                {
                    if ( if_detected )
                    System.out.println("USB "+drive_name[i]+" detected ");
 
                    usb_detected[i] = if_detected;
                }
 
        }
 
    }
    }

In the above program, we create a String array and store the external drive names in that array.
Then we search each drive with the help of canRead() method which returns a boolean value
and if the value returned is True then the USB is detected.


Output:-
Insert USB
USB E detected

I hope this article was useful. If any doubts or suggestions leave a comment down below.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *