I currently have 2 very annoying problems when I'm trying to download files through Java.

When I try to download 20 .jpg files from an website (Files with the same name followed by a different number) it only downloads 6-7 files and then stops half-way. Here is my code:

Java Code:
public class FileDownload2 {
	public static void main(String [] args) {
		URL url;
        URLConnection con;
        DataInputStream dis;
        FileOutputStream fos;
        byte[] fileData;
        String fname = null;
        for (int n = 1; n < 20; n++){
            fname = "picture-" + n + ".jpg";
            try {   
                url = new URL("http://randomwebsite.com/content/" + fname);
                con = url.openConnection();
                dis = new DataInputStream(con.getInputStream());
                fos = new FileOutputStream(new File("C:\\Users\\UserName\\Desktop\\content\\" + fname));
                final byte[] buf = new byte[1024];
                fileData = new byte[con.getContentLength()];
                for (int num = dis.read(buf); num != -1; num = dis.read(buf)) {
                	fos.write(buf, 0, num);
            catch(MalformedURLException m) {
            catch(IOException io) {

What could the problem be?

Also another problem where I try to download only 1 file with the same code (Just edited so it doesn't have the 'for') and the file is 2 mb or more, it stops when downloading. Sometimes when it's only downloaded 100 kb, sometimes when it's downloaded 1 mb. Thank you for your help!