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
. I tried to do that in the following way (executed with 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. No files can be found in it and if I try to mkdir
it will say "structure needs cleaning".
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.
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. 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.