I have a 200kb file and I have to read it in bytes, and then write part of this byteArray (from index 90000 to 165000) to another file. How can I accomplish this.
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) {}
Advertisement
Answer
Use a RandomAccessFile
in order to seek to the offset to start copying from.
For example:
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); }