bien!esta es la segunda forma
Código
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author Leyer
*/
public class ThreadForDownload extends Thread{
public static void main(String []args){
try {
new ThreadForDownload(new URL("http://www.tecnun.es/asignaturas/Informat1/ayudainf/aprendainf/Java/Java2.pdf"),"/home/leyer").start();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private URL url = null;
private URLConnection connection = null;
private int offset = 0;
private boolean init = true;
String path;
private FileOutputStream fileOutputStream;
public ThreadForDownload(
final URL URL,
String path) {
this.url = URL;this.path = path;
}
@Override
public synchronized void run() {
while(init){
try {
System.out.println("-----------------------------------");
System.out.println("Host: "+url.getHost());
System.out.println("NOmbre del Archivo: "+getFileName(url));
System.out.println("Tamaño: "+getLength(url));
System.out.println("-----------------------------------");
connection = url.openConnection();
} catch (IOException e) {System.err.println("Error in conection!");System.exit(0);
} catch (Exception e) {
e.printStackTrace();System.exit(0);
}
int read = 0;
final int SIZE = getLength(url);
InputStream stream = null;
try {
System.out.println("wait...");
stream = connection.getInputStream();
fileOutputStream = new FileOutputStream(path+""+File.separator+getFileName(url));
final byte[] data = new byte[SIZE];
while((read = stream.read(data)) > 0){
offset +=read;
fileOutputStream.write(data,
0,
read);
}
try{
System.out.println("Completado!");
fileOutputStream.flush();
fileOutputStream.close();
offset = 0; init = false;
break;
}catch (Exception e) { }
}catch (Exception e1) {
}
}
}
public void setInit(boolean init) {
this.init =false;
}
final int getLength(URL urlFile){
URLConnection connection = null;
int size = 0;
try {
connection = urlFile.openConnection();
size = connection.getContentLength();
} catch (IOException e) {
System.err.println(e+":ERROR");System.exit(0);
} catch (Exception e) {
System.err.println(e+":ERROR");System.exit(0);
}
return size;
}
private final String getFileName(URL URL){
String path=URL.getPath();
int lastIndexOf=path.lastIndexOf("/");
String name = path.substring(lastIndexOf+1);
return name;
}
}
PD: lo hice al instante asi que errores en el codigo se aceptan










Autor





En línea







