Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.saveweb3;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import org.apache.http.HttpStatus;
- import android.support.v7.app.ActionBarActivity;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.os.Environment;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.TextView;
- public class MainActivity extends ActionBarActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- TextView myTextView = (TextView) findViewById(R.id.helloW);
- new Download().execute();
- myTextView.setText("Done");
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- }
- class Download extends AsyncTask<Void, Void, Void> {
- @Override
- protected Void doInBackground(Void... params) {
- try {
- File SDCardRoot = Environment.getExternalStorageDirectory();
- String filename= "effortback.txt";
- File file = new File(SDCardRoot + "/",filename);
- file.createNewFile();
- FileOutputStream fileOutput = new FileOutputStream(file);
- URL url = new URL ("http://www.example.com/index.html");
- HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
- urlConnection.setRequestMethod("GET");
- urlConnection.setDoOutput(false);
- urlConnection.connect();
- InputStream inputStream;
- int status = urlConnection.getResponseCode();
- if(status >= HttpStatus.SC_BAD_REQUEST)
- inputStream = urlConnection.getErrorStream();
- else
- inputStream = urlConnection.getInputStream();
- int totalSize = urlConnection.getContentLength();
- int downloadedSize = 0;
- byte[] buffer = new byte[2048];
- int bufferLength = 0;
- while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
- fileOutput.write(buffer, 0, bufferLength);
- downloadedSize += bufferLength;
- }
- fileOutput.close();
- if(downloadedSize==totalSize) {
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment