4

好的,所以相信我,我想这样做是有原因的。也许不使用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.");
        }
    }

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

干杯

4

1 回答 1

3

您的问题是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();

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

于 2016-01-12T11:11:11.447 回答