Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.util.Log;

public class Main {
    public static void DownloadFromUrl(String thisUrl, String path, String filename) {
        Log.d("DownloadFromUrl", "url: " + thisUrl);
        Log.d("DownloadFromUrl", "path: " + path);
        Log.d("DownloadFromUrl", "filename: " + filename);
        try {
            URL url = new URL(thisUrl);
            new File(path).mkdirs();
            File file = new File(path, filename);

            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            Log.d("DownloadFromUrl", "about to write file");
            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            try {
                OutputStream os = new FileOutputStream(file);
                try {
                    byte[] buffer = new byte[4096];
                    for (int n; (n = is.read(buffer)) != -1;)
                        os.write(buffer, 0, n);
                } finally {
                    os.close();
                }
            } finally {
                is.close();
            }
            Log.d("DownloadFromUrl", "finished");

        } catch (IOException e) {
            Log.d("DownloadFromUrl", "Error: " + e);
        }
    }
}