0

This is my code.

while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read
{   
    download.removeMouseListener(m);
    /*speed.setText(String.valueOf(count));*/
    if (time >= time2 ){ // every second , set kb/s
        long initTimeInSeconds = initTime/1000000000;
        long currentTimeInSeconds = time/1000000000;
        speed.setText(String.valueOf((fout.getChannel().size() / 1024) / (currentTimeInSeconds-initTimeInSeconds) + "KB/s")); // set kb/s
        time2 = System.nanoTime() + 1000000000;
    }

    progress.setValue((int) fout.getChannel().size());//update progress bar
    fout.write(data, 0, count); // write the data to the file
    time = System.nanoTime();
} 

Essentially, the downloading code is just this :

while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read
{   
    fout.write(data, 0, count); // write the data to the file
    time = System.nanoTime();
} 

Where

byte data[] = new byte[16384];
BufferedInputStream in = null;
in = new BufferedInputStream(url.openStream());
int count = 0;

Somehow this code isn't downloading certain files, for example this file. http://nmap.org/dist/nmap-6.40-setup.exe

The while loop just dies off at start, it reads for 2 times and totally stops.

Can anyone explain why?

morgano
  • 17,210
  • 10
  • 45
  • 56
user2519193
  • 211
  • 2
  • 14

2 Answers2

2

This code just works fine for me. The code below downloads the file and write into the disk.

            URL url = new URL("http://nmap.org/dist/nmap-6.40-setup.exe");
    url.openConnection();
    byte data[] = new byte[16384];
    BufferedInputStream in = null;
    in = new BufferedInputStream(url.openStream());
    int count = 0;
    OutputStream fout =  new FileOutputStream("C:/test.exe");
    while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read
    {   
        fout.write(data, 0, count); // write the data to the file
        long time = System.nanoTime();
        System.out.println(time);
    } 
    fout.flush();
    fout.close();

The Only one possible failure i see is, if the output stream is not closed properly. Chances that the file may not be flushed into the disk.

Prem
  • 329
  • 1
  • 11
  • Thanks for replying, I found out the problem lies in my school network, apparantly my application doesn't want to work with it. Maybe it's the port number, is it possible to change what port I use to download the file? – user2519193 Aug 02 '13 at 06:32
  • You can't change the port. The server will have to ask the client to change the port, note the client – Prem Aug 02 '13 at 12:25
0
            URL url = new URL(logoPath);
            in = new BufferedInputStream(url.openStream());
            while (true) {

                if (in.available() == Integer.parseInt(app.getCoversize()))
                    break;
            }

file size = app.getCoversize();

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33