Java读取磁盘指定扇区

读取磁盘的指定扇区内容,基于Java实现,要求root权限。


/**
 * 读取磁盘或TF卡指定扇区
 * @param device 设备,如/dev/sda
 * @param sector 扇区号
 * @param size 扇区大小,字节
 * @return 扇区内容
 */
public byte[] readDiskSector(String device, int sector, int size) throws IOException {
    byte[] sectorBytes = null;
    FileChannel fc = null;
    try {
        Path fp = Paths.get(device);
        fc = FileChannel.open(fp, EnumSet.of(StandardOpenOption.READ));
        ByteBuffer buffer = ByteBuffer.allocate(size);
        fc.read(buffer, sector * size);
        fc.close();
        sectorBytes = buffer.array();
    }
    finally {
        if(fc != null)
            fc.close();
    }
    return sectorBytes;
}


如果磁盘为/dev/sda,扇区大小为512字节,读取第1024扇区,则执行:

byte[] sectorBytes = readDiskSector("/dev/sda", 1024, 512);




猜你喜欢

转载自blog.51cto.com/boytnt/2496974