JAVA CODE TO DETECT USB PORT [PEN DRIVE] AND DISPLAY ITS CONTENTS

import java.io.*;

class PenDrive implements Runnable
{

public PenDrive()
{

}
}

public class FindDrive
{

public static void main(String[] RK)
{
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];
int totFiles=0,totDirs=0;

// 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…”);

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 )
{
String path=letters[i]+”://”;
File files=new File(path);
String allFiles[]=files.list();

for(int k=0; k<allFiles.length; k++)
{
File f=new File(path+”/”+allFiles[k]);
if(f.isDirectory())
{
totDirs++;
System.out.println(“Directory :”+allFiles[k]);
}
else
{
totFiles++;
System.out.println(“File :”+allFiles[k]);
}
}
System.out.println(“Total Directories and Files :”+allFiles.length);
System.out.println(“Total Directories :”+allFiles.length);
System.out.println(“Total Files :”+allFiles.length);
}
else
{
System.out.println(“Drive “+letters[i]+” has been unplugged”);
}

isDrive[i] = pluggedIn;
}
}

try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{ }
}
}
}

Thank You.

Advertisements

About rajkirpal

i am a software engineer. and i have decent knowledge about java technologies like ANDROID, Servlet, Jsp, Struts, Hibernet, Spring, J2ME, Java Script, Ajax, JQuery, CSS. Further i am Preparing Easy understandable materials/documents upon the same java technologies and developing project in core java , advanced java and j2me , ANDROID as per the requirements Also designing the web sites and logos Thank You.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s