Copy file using read and write streams I have this piece of code in my program, where I assign 10000 as the size of the buffer. Now How can I check if the file that I am copying is less than 10000, for example 5000, than how to free the remaining 5000 back?
Thank You.
private void copyFile(File in, File out) {
        var buffer = new byte[10000];
        try {
            FileInputStream dis = new FileInputStream(in);
            FileOutputStream dos = new FileOutputStream(out);
            int count;
            do {
                count = dis.read(buffer);
                if (count != -1)
                    dos.write(buffer, 0, count);
            } while (count != -1);
            dis.close();
            dos.close();
        } catch (IOException e) {
            program.print(&quot;Error copying file: &quot; + e.toString() + &quot;\n&quot;, null);
        }
    }

EDIT: Is there anyway, I can optimize this more?
Streams should always be closed. You will have resource leaks if your method throws an exception. Either close the streams in a finally block, or use try-with-resources to make sure they get closed.
Optional curly braces aren't. Skipping them will often lead to bugs when code gets modified later.
The typical loop structure used for working with streams looks more like
int charsRead;
while ((charsRead = dis.read(buffer) &gt; 0) {
    // do stuff
}

10,000 is pretty big for a buffer. That may not be the best choice.
Please don't swallow the stack trace. That's critical information when this code needs to be debugged later.
Opinion: var is icky.
If you apply all these changes, your code might look more like:
private void copyFile(File in, File out) {
    byte[] buffer = new byte[1024];
    try (FileInputStream dis = new FileInputStream(in);
            FileOutputStream dos = new FileOutputStream(out)) {
        int charsRead;
        while ((buffer = dis.read(buffer) &gt; 0) {
                dos.write(buffer, 0, charsRead);
        }
    } catch (IOException e) {
        //I don't know how to use your logging library to display exception stack trace, so..
        e.printStackTrace(System.err);
    }
}

Of course, this is assuming that you can't use the rather intuitively named Files.copy() instead. That would be much better.
private void copyFile(File in, File out) {
    try {
        Files.copy(in.toPath(), out.toPath());
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}