Ritesh Bhakre
Ritesh Bhakre

Reputation: 203

File-oriented operation via java

I'm trying to copy the "contents" of a particular .mp4(video) file into another via the following code:

Path source = Paths.get("E:\\Video0001.mp4");
Path destination = Paths.get("C:\\Ritesh\\Experimentation\\GOT.mp4");  
Set<OpenOption> options = new HashSet<>();
options.add(APPEND);
options.add(CREATE);
try (SeekableByteChannel sbc = Files.newByteChannel(source);
        SeekableByteChannel sbcdes = Files.newByteChannel(destination, options)) {
    ByteBuffer buf = ByteBuffer.allocate(10);
    String encoding = System.getProperty("source.encoding");
    while (sbc.read(buf) > 0) {
        buf.rewind();

        ByteBuffer bb =  
            ByteBuffer.wrap(((Charset.forName(encoding).decode(buf)).toString()).getBytes());
        sbcdes.write(bb);   
        buf.flip();
    }
} catch (IOException x) {
    System.out.println("caught exception: " + x);
}

The code executes, a destination .mp4 file is created at the desired location but the predicament is that the .mp4 file won't run....it gives me an error message, stating the input's format can't be recognized... File operations are still a novelty to me, rendering me unable to resolve this conundrum.... any form of assistance would be ecstatically appreciated! =)

Upvotes: 1

Views: 101

Answers (1)

The problem is that you are decoding and encoding the data (converting it to Strings and back). This mangles anything that's not text. MP4 files aren't text.

This should work, instead of the loop you have:

while (sbc.read(buf) > 0) {
    buf.flip()
    sbcdes.write(buf);
    buf.clear();
}

Upvotes: 3

Related Questions