如何在 Java 中获得具有写入权限的原始磁盘访问 - Windows 7

Azu*_*ake 5 java io disk

好吧,相信我,我这样做是有原因的。也许没有使用 Java,但确实有。我可以使用 UNC 样式路径在 Windows 7 上原始访问磁盘,例如:

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.");
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我切换到“rw”模式,则会出现 NullPointerException,即使我以管理员身份运行该程序,也无法获得对磁盘进行原始写入的句柄。我知道已经有人问过这个问题了,但主要是为了阅读……那么,写作呢?我需要 JNI 吗?如果是这样,有什么建议吗?

干杯

Dan*_*der 4

您的问题是new RandomAccessFile(drivepath, "rw")使用与原始设备不兼容的标志。为了写入这样的设备,您需要 Java 7 及其新的nio类:

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();
Run Code Online (Sandbox Code Playgroud)

(答案取自另一个(类似)问题