Java读取磁盘指定扇区

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

 1 /**
 2  * 读取磁盘或TF卡指定扇区
 3  * @param device 设备,如/dev/sda
 4  * @param sector 扇区号
 5  * @param size 扇区大小,字节
 6  * @return 扇区内容
 7  */
 8 public byte[] readDiskSector(String device, int sector, int size) throws IOException {
 9     byte[] sectorBytes = null;
10     FileChannel fc = null;
11     try {
12         Path fp = Paths.get(device);
13         fc = FileChannel.open(fp, EnumSet.of(StandardOpenOption.READ));
14         ByteBuffer buffer = ByteBuffer.allocate(size);
15         fc.read(buffer, sector * size);
16         fc.close();
17         sectorBytes = buffer.array();
18     }
19     finally {
20         if(fc != null)
21             fc.close();
22     }
23 
24     return sectorBytes;
25 }

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

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

 

原文地址:https://www.cnblogs.com/BoyTNT/p/12923757.html