0

I have an mp3 link i want to download from java just for testing. Here is what i code to do that

private void saveFile() throws Exception{
        System.out.println("Opening InputStream.");
        InputStream is =  fileUrlConnection.getInputStream();
        System.out.println("Total: "+is.available()+" bytes");
        FileOutputStream fos = new FileOutputStream(new File("hello.mp3"));
        byte[] buffer = new byte[1024];
        while (is.read(buffer)!= -1) {
            fos.write(buffer);
        }
        is.close();
        fos.close();
    }

Above method throws an exception after a number of calls.

java.net.SocketException: Unexpected end of file from server
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at com.jwc.FileSaver.saveFile(FileSaver.java:24)
    at com.jwc.FileSaver.run(FileSaver.java:39)
    at java.lang.Thread.run(Unknown Source)
user207421
  • 305,947
  • 44
  • 307
  • 483
Usman Riaz
  • 2,920
  • 10
  • 43
  • 66
  • How do you know it's not getting past that line? Does `getInputStream` throw an exception? btw. `is.read()` returns the number of bytes that were read. You can't just ignore that number. – Tesseract Feb 14 '16 at 04:38
  • sorry, it does throws exception. kindly have a look at my question again thank you – Usman Riaz Feb 14 '16 at 04:43
  • You have to catch the exception and then you can either download the file again or hope that it's complete despite of that error. You can also try to resume the download at the point it stopped as explained in this question. http://stackoverflow.com/questions/3411480/how-to-resume-an-interrupted-download – Tesseract Feb 14 '16 at 04:59
  • You're misusing `available(),` and you aren't using the value returned by `read()` correctly. You need to provide it as the third parameter to `write().` – user207421 Feb 14 '16 at 09:02
  • @SpiderPig The download hasn't even started, let alone any possibility of it being complete. See the stack trace. – user207421 Feb 14 '16 at 10:53

3 Answers3

0

Try next code, it should work:

BufferedInputStream in = null;
FileOutputStream fout = null;
try {
    in = fileUrlConnection.getInputStream();
    fout = new FileOutputStream(new File("hello.mp3"));

    final byte data[] = new byte[1024];
    int count;
    while ((count = in.read(data)) != -1) {
        fout.write(data, 0, count);
    }
} finally {
    if (in != null) {
        in.close();
    }
    if (fout != null) {
        fout.close();
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Dmitry Kolesnikovich
  • 669
  • 2
  • 15
  • 33
0

If you are using at last Java 7, you can use Files.copy. The example given there is exacly what you want: "... to capture a web page and save it to a file"

    try (InputStream is =  fileUrlConnection.getInputStream()) {
        Files.copy(is, Paths.get("hello.mp3"));
    }
Daniel Fekete
  • 4,988
  • 3
  • 23
  • 23
0

I suggest using the New IO to solve this question:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Main {
    public static void main(String[] args) throws IOException {
        URL url = null;
        ReadableByteChannel in = null;
        SeekableByteChannel out = null;
        try {
            url = new URL("https://img1.goodfon.ru/original/3216x2072/f/56/samoed-sobaka-belaya-yazyk-trava.jpg");
            URLConnection cc = url.openConnection();
            in = Channels.newChannel(cc.getInputStream());
            out = Files.newByteChannel(Paths.get("dog.jpg"), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            ByteBuffer buf = ByteBuffer.allocate(1024);
            while (in.read(buf) != -1) {
                buf.flip();
                out.write(buf);
                buf.rewind();
                buf.limit(buf.capacity());
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }
}
Antonio
  • 304
  • 2
  • 11