ICeQ
ICeQ

Reputation: 152

How to read disk partition in java

Is it possible to read whole partition of disk in java?

Partition is treated as directory (obviously) and because of it I can't create FileInputStream which I need.

I'd like to compute hash for whole partition of disk (byte by byte) and I was wondering how to achieve that.

If that matters it has to work both on Windows and Linux.

Any thoughts are appreciated!

Upvotes: 0

Views: 1356

Answers (2)

ICeQ
ICeQ

Reputation: 152

As @Michal suggested I've changed path to partition to "\\.\X:" convention.

Code looks like this:

File diskRoot = new File("\\\\.\\F:");
byte[] buffer = new byte[1024];
try (InpuStream stream = new FileInputStream(diskRoot)) {
    while(stream.read(buffer) != -1) {
        //do something with buffer
    }
} catch(IOException e) {
    //handle exception
}

Thanks for the comments and answers!

Upvotes: 1

Michal
Michal

Reputation: 6742

Try that with administrator's permissions:

File diskRoot = new File ("\\.\X:"); //X is your requested partition's letter 
RandomAccessFile diskAccess = new RandomAccessFile(diskRoot, "r");
byte[] content = new byte[1024];
diskAccess.readFully (content);

You can also use BufferedInputStream. It's the hunsricker's answer from How to access specific raw data on disk from java

The naming convention can be found here: http://support.microsoft.com/kb/100027

Upvotes: 2

Related Questions