读取十六进制 byteArray 中的文件并将该数组的一部分写入另一个文件 - java android
read a File in hex byteArray and write part of that array to another File - java android
我有一个 200kb 的文件,我必须以字节为单位读取它,然后将这个 byteArray 的一部分(从索引 90000 到 165000)写入另一个文件。我怎样才能做到这一点。
File file1 = new File(getExternalStorageDirectory(), "file1.raw"); //the 200kb file
try {
File.createTempFile("file2", "mp3", getCacheDir()); //empty file that needs to get filled with part of the byte array from file1
} catch (IOException ignored) {}
使用 RandomAccessFile
以查找开始复制的偏移量。
例如:
final int bufSize = 1024; // the buffer size for copying
byte[] buf = new byte[bufSize];
final long start = 10000L; // start offset at source
final long end = 15000L; // end (non-inclusive) offset at source
try (
RandomAccessFile in = new RandomAccessFile("input.bin", "r");
OutputStream out = new FileOutputStream("output.bin"))
{
in.seek(start);
long remaining = end - start;
do {
int n = (remaining < bufSize)? ((int) remaining) : bufSize;
int nread = in.read(buf, 0, n);
if (nread < 0)
break; // EOF
remaining -= nread;
out.write(buf, 0, nread);
} while (remaining > 0);
}
我有一个 200kb 的文件,我必须以字节为单位读取它,然后将这个 byteArray 的一部分(从索引 90000 到 165000)写入另一个文件。我怎样才能做到这一点。
File file1 = new File(getExternalStorageDirectory(), "file1.raw"); //the 200kb file
try {
File.createTempFile("file2", "mp3", getCacheDir()); //empty file that needs to get filled with part of the byte array from file1
} catch (IOException ignored) {}
使用 RandomAccessFile
以查找开始复制的偏移量。
例如:
final int bufSize = 1024; // the buffer size for copying
byte[] buf = new byte[bufSize];
final long start = 10000L; // start offset at source
final long end = 15000L; // end (non-inclusive) offset at source
try (
RandomAccessFile in = new RandomAccessFile("input.bin", "r");
OutputStream out = new FileOutputStream("output.bin"))
{
in.seek(start);
long remaining = end - start;
do {
int n = (remaining < bufSize)? ((int) remaining) : bufSize;
int nread = in.read(buf, 0, n);
if (nread < 0)
break; // EOF
remaining -= nread;
out.write(buf, 0, nread);
} while (remaining > 0);
}