1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
package update;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Download
{
public static void getFile(String host)
{
InputStream input = null;
FileOutputStream writeFile = null;
try
{
URL url = new URL(host);
URLConnection connection = url.openConnection();
int fileLength = connection.getContentLength();
if (fileLength == -1)
{
System.out.println("Invalide URL or file.");
return;
}
input = connection.getInputStream();
String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
writeFile = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0)
writeFile.write(buffer, 0, read);
writeFile.flush();
}
catch (IOException e)
{
System.out.println("Error while trying to download the file.");
e.printStackTrace();
}
finally
{
try
{
writeFile.close();
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
} |
Partager