How to access raw drive in Java with write permissions - Windows 7

Okay, so trust me that I want to do this. Maybe not using Java, but there is. I can perform raw disk access in Windows 7 using 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 is thrown, and even I run the program as an administrator, I do not get a handle to raw write to disk. I know this has already been asked, but mainly for reading ... so, what about writing? Do I need JNI? If so, any suggestions?

Greetings

+4
source share
1 answer

Your problem is that new RandomAccessFile(drivepath, "rw") uses flags that are not compatible with raw devices. To write to such a device, you need Java 7 and the new nio class:

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

(the answer is made from another (similar) question)

+2
source

Source: https://habr.com/ru/post/1491735/


All Articles