How to access specific raw data on disk from java

I was looking by myself for a possibility to access raw data form a physical drive. And now as I got it to work, I just want to tell you how. You can access raw disk data directly from within java ... just run the following code with administrator priviliges:

    File diskRoot = new File ("\\\\.\\PhysicalDrive0");
    RandomAccessFile diskAccess = new RandomAccessFile (diskRoot, "r");
    byte[] content = new byte[1024];
    diskAccess.readFully (content);

So you will get the first kB of your first physical drive on the system. To access logical drives - as mentioned above - just replace 'PhysicalDrive0' with the drive letter e.g. 'D:'

oh yes ... I tried with Java 1.7 on a Win 7 system ...

Just have a look at the naming of physical drives at http://support.microsoft.com/kb/100027/en-us


If you are interested in writing to a raw volume under Windows, try this (needs Java 7).

  String pathname;
  // Full drive:
  // pathname = "\\\\.\\PhysicalDrive0";
  // A partition (also works if windows doesn't recognize it):
  pathname = "\\\\.\\GLOBALROOT\\ArcName\\multi(0)disk(0)rdisk(0)partition(5)";

  Path diskRoot = ( new File( pathname ) ).toPath();

  FileChannel fc = FileChannel.open( diskRoot, StandardOpenOption.READ,
        StandardOpenOption.WRITE );

  ByteBuffer bb = ByteBuffer.allocate( 4096 );

  fc.position( 4096 );
  fc.read( bb );
  fc.position( 4096 );
  //fc.write( bb ); // careful!

  fc.close();

Of course, you have to make sure the device is writable and not accessed/locked by the system. Also make sure your application runs with the necessary privileges (elevated privileges).

Btw: Using new RandomAccessFile(drive, "rw") doesn't seem to work because Java doesn't open the file handle in a mode which is compatible to raw devices (exception is java.io.FileNotFoundException (The parameter is incorrect)). But reading works fine also with RandomAccessFile.


RandomAccessFile is not meant to open directories to manipulate entries, you need to create or remove files. "Acceso denegado" probably mean access denied. To do this anyway you need JNI.

EDIT: What you are trying to do, is really complicated, there is no common way to do that. You can access the harddisc sector by sector, but then you would have to interpret it's structure, which obviously depends on the file system, FAT,NTFS,HPFS etc.

Tags:

Java

Drive