1

I'm trying to find a way to use

copyInputStreamToFile(InputStream source, File destination)

to make a small progress bar in the console by file size. Is there a way to do this?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
Shadow
  • 170
  • 1
  • 11

1 Answers1

2

The short answer you can't, look at the source code of this method, I tried to track its execution path and it goes to this method at IOUtils class:

 public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
                throws IOException {
            long count = 0;
            int n = 0;
            while (EOF != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
                count += n;
            }
            return count;
        }

So, this functionality is encapsulated by an API.

The long answer you can implement downloading method by yourself, by using relative parts of IOUtils and FileUtils libraries and add functionality to print percentage of downloaded file in a console:

This is a working kick-off example:

package apache.utils.custom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class Downloader {

    private static final int EOF = -1;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;


    public static void copyInputStreamToFileNew(final InputStream source, final File destination, int fileSize) throws IOException {
        try {

            final FileOutputStream output = FileUtils.openOutputStream(destination);
            try {

                final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                long count = 0;
                int n = 0;
                while (EOF != (n = source.read(buffer))) {
                    output.write(buffer, 0, n);
                    count += n;
                    System.out.println("Completed " + count * 100/fileSize + "%");
                }

                output.close(); // don't swallow close Exception if copy completes normally
            } finally {
                IOUtils.closeQuietly(output);
            }

        } finally {
            IOUtils.closeQuietly(source);
        }
}

You should provide expected file size to this method which you can calculate by using this code:

        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        int file_size = urlConnection.getContentLength();

Of course the better idea is to encapsulate the whole functionality in a single method.

Hope it will help you.

Community
  • 1
  • 1
Anatoly
  • 5,056
  • 9
  • 62
  • 136