5

OK, so trust me there's a reason I want to do this. Maybe not using Java, but there is. I am able to raw access the disk on Windows 7 using the UNC-style paths, for example:

RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile("\\\\.\\PhysicalDrive0","r");
        byte [] block = new byte [2048];
        raf.seek(0);
        raf.readFully(block);
        System.out.println("READ BYTES RAW:\n" + new String(block));
    } catch (IOException ioe) {
        System.out.println("File not found or access denied. Cause: " + ioe.getMessage());
        return;
    } finally {
        try {
            if (raf != null) raf.close();
            System.out.println("Exiting...");
        } catch (IOException ioe) {
            System.out.println("That was bad.");
        }
    }

But if I switch to "rw" mode, a NullPointerException arises and even I run the program as an Administrator, I'm not getting the handle for raw writing to the disk. I know this has been asked already, but mainly for reading... so, what about writing? Do I need JNI? If so, any suggestions?

Cheers

Azurlake
  • 612
  • 1
  • 6
  • 29
  • Same problem here. In my case, the exception is: `java.io.FileNotFoundException: \\.\GLOBALROOT\ArcName\multi(0)disk(0)rdisk(0)partition(5) (Falscher Parameter) at java.io.RandomAccessFile.open(Native Method) at java.io.RandomAccessFile.(Unknown Source)` hope this help for finding the solution. `"r"` works fine too – Daniel Alder Oct 31 '13 at 14:04
  • 1
    @DanielAlder it seems you later solved it. http://stackoverflow.com/a/19723977/1378620 – Robert Jan 12 '16 at 10:44

1 Answers1

4

Your problem is that new RandomAccessFile(drivepath, "rw") uses flags which are not compatible to raw devices. For writing to such a device, you need Java 7 and its new nio classes:

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 );

fc.close();

(answer taken from another (similar) question)

Community
  • 1
  • 1
Daniel Alder
  • 5,031
  • 2
  • 45
  • 55