Я пытаюсь загрузить файл с URL.Мой код не возвращает ошибку, но я не вижу файл, который должен загрузить во внутреннюю память.Вот мой код:
package com.example.downloadfile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
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 {
URL url = new URL("http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getDataDirectory() + "/";
tv.append("\nPath > " + PATH);
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: ");
tv.append("\nAnother append!");
this.setContentView(tv);
}
}
Я новичок в Java и Android Dev, любые ответы будут высоко оценены, спасибо!
Йо!Я использовал фф.код вместоЭто работает для меня.Спасибо за вашу помощь!
private static String fileName = "beautiful_galaxy - tarantula.jpg";
private static String fileURL = "http://apod.nasa.gov/apod/image/0903/tarantula2_hst_big.jpg";
try {
File root = Environment.getExternalStorageDirectory();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}