[英]Copy raw data of block device using Java
我在 Linux 系統中有 2 個磁盤,例如/dev/dsk1
和/dev/dsk2
,我正在嘗試從dsk1
讀取原始數據(以字節為單位)並將它們寫入dsk2
,以使dsk2
成為dsk1
的精確副本. 我嘗試通過以下方式執行此操作(使用sudo
執行):
import...
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
Path src = new File("/dev/dsk1").toPath();
Path dst = new File("/dev/dsk2").toPath();
FileChannel r = FileChannel.open(src, StandardOpenOption.READ, StandardOpenOption.WRITE);
FileChannel w = FileChannel.open(dst, StandardOpenOption.READ, StandardOpenOption.WRITE);
long size = r.size();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
for (int offset = 0; offset < size; offset+=1024) {
r.position(offset);
w.position(offset);
r.read(byteBuffer);
byteBuffer.flip();
w.write(byteBuffer);
byteBuffer.clear();
}
r.close();
w.close();
}
}
但是在將 dsk1 中的所有字節寫入dsk1
dsk2
, dsk2
的文件系統似乎已損壞。 在其中找不到任何文件,如果我嘗試mkdir
,它會說“結構需要清理”。
我已經在常規文件上測試了上面的代碼,比如一個text1.txt
包含幾個字符作為src
和一個空的text2.txt
作為dst
,它工作正常。
在塊設備上讀取和寫入原始數據時我錯過了什么嗎?
您永遠不會檢查read
方法是否讀取了所有 1024 個字節,或者write
方法是否將它們全部寫入。 您很可能會在副本中留下空白。
讀取和寫入設備沒有任何魔法。 我會嘗試的第一件事是:
try (FileInputStream src = new FileInputStream("/dev/dsk1");
FileOutputStream dst = new FileOutputStream("/dev/dsk2")) {
src.transferTo(dst);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.