try {
// Khai báo url
URL url = new URL("http://somewhere.com/some/webhosted/file");
//tạo HTTP connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//setup phương thức cho HTTP connecton
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
// kết nối
urlConnection.connect();
// khởi tạo sdcard . Lưu ý phương thức Environment.getExternalStorageDirectory(); trả lại đường dẫn đến sdcard
File SDCardRoot = Environment.getExternalStorageDirectory();
// Tạo 1 file để lưu nội dung trang web
File file = new File(SDCardRoot,"somefile.ext");
//Khai báo FileInputStream để tương tác với InputStream
FileOutputStream fileOutput = new FileOutputStream(file);
//InputStream để đọc dẽ liệu từ url
InputStream inputStream = urlConnection.getInputStream();
//lấy size của dữ liệu tải về
int totalSize = urlConnection.getContentLength();
// khai báo 1 biến để biết dữ liệu tải về ( realtime)
int downloadedSize = 0;
//tạo buffer
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//đọc dữ liệu từ buffer
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//ghi từ buffer vào textfile ở sdcard
fileOutput.write(buffer, 0, bufferLength);
//update downloadSize
downloadedSize += bufferLength;
//dựa vào biến downloadSize để update progess
updateProgress(downloadedSize, totalSize);
}
//đóng outputstream khi hoàn thành
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Subscribe to:
Post Comments (Atom)
Popular Posts
-
I spent a long time to config them. so tired, but now it run very good. It's work. Step 1: Download Source PhoneGap at PhoneGap.com...
-
Để chuyển 1 file .app sang .ipa đầu tiên các bận cần có là 1 file .app, trong hướng dẫn mình sử dụng file Tuvi.app 1. Mở xcode len 2. Men...
-
Trong bài này mình sẽ giới thiệu với các bạn về lập trình Socket(bài này mình chỉ nói đến lập trình Socket cho TCP/IP) trong Android. Lập ...
-
Xử lý ngày tháng trong PHP Trừ ngày $date = "2009-03-02"; $new_date = strtotime ( '-2 day' , strtotime ( $date ) ) ; ...
No comments:
Post a Comment