How to access specific raw data on disk from java

前端 未结 8 643
一向
一向 2020-11-28 07:59

I\'m trying to use the following code to access one byte with offset of 50 bytes in a raw disk.

randomAccessFile = new RandomAccessFile(\"C:\", \"r\");
rando         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 08:09

    If you are interested in writing to a raw volume under Windows, try this (needs Java 7).

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

    Of course, you have to make sure the device is writable and not accessed/locked by the system. Also make sure your application runs with the necessary privileges (elevated privileges).

    Btw: Using new RandomAccessFile(drive, "rw") doesn't seem to work because Java doesn't open the file handle in a mode which is compatible to raw devices (exception is java.io.FileNotFoundException (The parameter is incorrect)). But reading works fine also with RandomAccessFile.

提交回复
热议问题