Gnanadeep Grandha
Gnanadeep Grandha

Reputation: 21

Detect a USB device plug in and out (kind of Listening) with Java? Not just pendrives

How can I detect a USB device plug in and out (kind of listening) with Java?
Not just a pendrive, it could be a scanner or printer too.

I tried jUSB, but it's of no use.
USB Java library would be more since I've got to use just a bit of it.

I need to include the lines in my code so that the device being plugged in and plugged out can be notified.

Upvotes: 0

Views: 2229

Answers (2)

I have written below to detect USB

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 ");
                    }else {
                        System.out.println("USB " + drive_name[i] + " removed ");
                    }
                    usb_detected[i] = if_detected;
                }

            }

        }
    }
}

Upvotes: 0

Vikas Suryawanshi
Vikas Suryawanshi

Reputation: 522

USB support in Java is limited to third party libraries. I've not used any of these but you could try JUSB

If you can't find a solution through a USB library you could always do a bit of a bodge job and loop through all likely drive letters creating a File object for each one and testing to see if you can read from it. If a USB memory device is plugged in, a drive letter that previously failed would now pass and so you would know you have a new device. Of course you don't know what sort of device it is (ie it could be a CD/DVD). But as I said this is not an ideal solution.

Here's a knocked up utility to prove the point

import java.io.*;

/**
* Waits for USB devices to be plugged in/unplugged and outputs a message
*/
public class FindDrive
{
/**
* Application Entry Point
*/
public static void main(String[] args)
{
String[] letters = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
boolean[] isDrive = new boolean[letters.length];

// init the file objects and the initial drive state
for ( int i = 0; i < letters.length; ++i )
    {
    drives[i] = new File(letters[i]+":/");

    isDrive[i] = drives[i].canRead();
    }

 System.out.println("FindDrive: waiting for devices...");

 // loop indefinitely
 while(true)
    {
    // check each drive 
    for ( int i = 0; i < letters.length; ++i )
        {
        boolean pluggedIn = drives[i].canRead();

        // if the state has changed output a message
        if ( pluggedIn != isDrive[i] )
            {
            if ( pluggedIn )
                System.out.println("Drive "+letters[i]+" has been plugged in");
            else
                System.out.println("Drive "+letters[i]+" has been unplugged");

            isDrive[i] = pluggedIn;
            }
        }

    // wait before looping
    try { Thread.sleep(100); }
    catch (InterruptedException e) { /* do nothing */ }

    }
 }
}

Upvotes: 0

Related Questions