Lorenz
Lorenz

Reputation: 39

Java - File Download makes Program Stop

When I download a file in Java with the following code, i can't use the Program anymore, it's not responding. But when the Download finishs i can use it again.

URL website = new URL("MY_URL");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("grafik");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

How do I fix that? E.g. that a loading screen is showed or that a dialog pops up? Thanks in Advance :D

Upvotes: 0

Views: 151

Answers (2)

ali köksal
ali köksal

Reputation: 1227

If you are developing a java desktop application and use Swing, SwingWorker is a nice way to do time consuming background tasks. It has built in support for updating progress info.

Upvotes: 0

asteri
asteri

Reputation: 11602

Time to learn about the wonderful world of concurrency!

new Thread(new Runnable() {
    @Override
    public void run() {
        URL website = new URL("MY_URL");
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream("grafik");
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    }
}).start();

Doing this will launch a separate thread -- essentially another line of execution hat acts independently of the one it's spawned from. This will allow your user interface to continue to function while this activity happens separately.

Concurrency can be very tricky, though, once you start wanting the different threads to interact. Definitely take a look at the Oracle tutorial linked in this post.

Upvotes: 2

Related Questions