简体   繁体   English

使用 Java 复制块设备的原始数据

[英]Copy raw data of block device using Java

I have 2 disks in the Linux system, say /dev/dsk1 and /dev/dsk2 , and I'm trying to read the raw data from dsk1 in bytes and write them into dsk2 , in order to make dsk2 an exact copy of dsk1 .我在 Linux 系统中有 2 个磁盘,例如/dev/dsk1/dev/dsk2 ,我正在尝试从dsk1读取原始数据(以字节为单位)并将它们写入dsk2 ,以使dsk2成为dsk1的精确副本. I tried to do that in the following way (executed with sudo ):我尝试通过以下方式执行此操作(使用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();
    }
}

but after writing all the bytes in dsk1 to dsk2 , dsk2 's filesystem seems to be corrupted.但是在将 dsk1 中的所有字节写入dsk1 dsk2dsk2的文件系统似乎已损坏。 No files can be found in it and if I try to mkdir it will say "structure needs cleaning".在其中找不到任何文件,如果我尝试mkdir ,它会说“结构需要清理”。

I've tested the above code on regular files, like a text1.txt containing a few characters as src and an empty text2.txt as dst , and it worked fine.我已经在常规文件上测试了上面的代码,比如一个text1.txt包含几个字符作为src和一个空的text2.txt作为dst ,它工作正常。

Did I miss something there when reading & writing raw data on block device?在块设备上读取和写入原始数据时我错过了什么吗?

You never check if read method read all 1024 bytes, or if write method wrote them all.您永远不会检查read方法是否读取了所有 1024 个字节,或者write方法是否将它们全部写入。 Most likely you're leaving gaps in the copy.您很可能会在副本中留下空白。

There's no magic involved reading from and writing to devices.读取和写入设备没有任何魔法。 The first thing I would try is this:我会尝试的第一件事是:

try (FileInputStream src = new FileInputStream("/dev/dsk1");
     FileOutputStream dst = new FileOutputStream("/dev/dsk2")) {
    src.transferTo(dst);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM