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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章