How to access specific raw data on disk from java

user178973 picture user178973 · Jan 21, 2010 · Viewed 16.7k times · Source

I'm trying to use the following code to access one byte with offset of 50 bytes in a raw disk.

randomAccessFile = new RandomAccessFile("C:", "r");
randomAccessFile.seek(50);
byte[] buffer = new byte[1];
randomAccessFile.read(buffer);

But all what I get is the following error:

java.io.FileNotFoundException: C: (Acceso denegado)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:98)
at pru.lseek.main(lseek.java:26)

Is there any way to access a precise byte in a drive from java?

Answer

hunsricker picture hunsricker · Dec 22, 2011

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