PDA

Visualizza la versione completa : [JAVA] Scaricare un file dal Web


sha
25-02-2006, 12:43
sto cercando di creare un metodo che permette di scaricare un file dal web, ma i file scaricati nn sono completi o cmq nn funzionano.
Qualcuno sa darmi qualche dritta?
questo il metodo da me fatto:





public boolean dwnFileFromWeb (String NameFile) throws MalformedURLException, IOException{
//mi collefo al file remoto
URL url = new URL(NameFile);
DataInputStream is = new DataInputStream(url.openStream());
//creo il file locale
File file = new File("temp_update");
FileOutputStream fos = new FileOutputStream(file);
//prelevo la dimensione del file
long fileSize=0;
while (is.read()>=0){
fileSize++;
}
//
is.close();

System.out.println(fileSize + " byte to download");

DataInputStream inStream = new DataInputStream(url.openStream());
BufferedInputStream bis=new BufferedInputStream(inStream);

byte inBuf[];
while (fileSize>0){
if(fileSize>=1024){
inBuf= new byte[1024];
}
else{
inBuf = new byte[(int)fileSize];
}
int bytesRead = bis.read(inBuf);
fos.write(inBuf);
fileSize=fileSize-1024;
}

//chiudo lo stream
inStream.close();
fos.close();

return true;
}
}

FelixR
25-02-2006, 13:09
se ti pu servire ho fatto questo, molto intuitivo:



public class FileDownload {
public static boolean download(URL fileToDownload, File location){
try {
URLConnection connection = fileToDownload.openConnection();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(location);;
long start=new Date().getTime();
long nbytes=copy(is,os);
long finish=new Date().getTime();
System.out.println("Download completato: "+location.getAbsolutePath());
System.out.println(nbytes+" bytes in "+((finish-start)/1000)+" seconds");
return true;
} catch (IOException e) {
System.err.println("Download fallito: "+location.getAbsolutePath());
e.printStackTrace();
return false;
}
}

public static long copy(InputStream in, OutputStream out) throws IOException{
long bytesCopied = 0;
byte[] buffer = new byte[4096];
int bytes;
try{
while ( (bytes = in.read( buffer )) != -1 ){
out.write( buffer, 0, bytes );
bytesCopied += bytes;
}
}finally{
in.close();
out.close();
}

return bytesCopied;
}
}

sha
25-02-2006, 14:06
perfetto funziona!!

grazie mille! :yuppi:

Loading