J'essaie de télécharger un fichier à partir d'une URL. J'ai le code suivant.
package com.example.downloadfile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadFile extends Activity {
private static String fileName = "al.jpg";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("This is download file program... ");
try {
//this is the file you want to download from the remote server
String path ="http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg";
//this is the name of the local file you will create
String targetFileName = "al.jpg";
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH_op = Environment.getExternalStorageDirectory() + "/download/" + targetFileName;
tv.append("\nPath > " + PATH_op);
FileOutputStream f = new FileOutputStream(new File(PATH_op));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
tv.append("\nAnother append!");
this.setContentView(tv);
}
}
Quelqu'un peut-il me dire ce qui ne va pas dans ce code ? Je n'arrive pas à voir le fichier que je suis censé télécharger. Je suis novice en java et en développement Android, merci pour toute aide :)