简体   繁体   English

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

[英]How to get raw disk access in Java with write permissions - Windows 7

OK, so trust me there's a reason I want to do this. 好的,相信我,这是我想要这样做的原因。 Maybe not using Java, but there is. 也许不使用Java,但是有。 I am able to raw access the disk on Windows 7 using the UNC-style paths, for example: 我可以使用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.");
        }
    }

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. 但是,如果我切换到“ rw”模式,则会出现NullPointerException,即使我以管理员身份运行该程序,也无法获取原始写入磁盘的句柄。 I know this has been asked already, but mainly for reading... so, what about writing? 我知道已经有人问过这个问题,但是主要是为了阅读...所以写作呢? Do I need JNI? 我需要JNI吗? If so, any suggestions? 如果是这样,有什么建议吗?

Cheers 干杯

Your problem is that new RandomAccessFile(drivepath, "rw") uses flags which are not compatible to raw devices. 您的问题是new RandomAccessFile(drivepath, "rw")使用的标志与原始设备不兼容。 For writing to such a device, you need Java 7 and its new nio classes: 要写入这样的设备,您需要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();

(answer taken from another (similar) question ) (答案来自另一个(类似) 问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM