Java讀取磁盤指定扇區

讀取磁盤的指定扇區內容,基於Java實現,要求root權限。java


/**
 * 讀取磁盤或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扇區,則執行:ide

byte[] sectorBytes = readDiskSector("/dev/sda", 1024, 512);
相關文章
相關標籤/搜索