Wednesday, September 15, 2010

Reading data from internet and writing to a file - Andorid

many a times we need to download a data from internet and save on our mobile... well theres an easy example for the same...
In this particular example, i have downloaded a pdf file from internet and saved in my data directory..

package abhi.pdf.downloader;

/*
Copyright [2010] [Abhinava Srivastava]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
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 android.app.Activity;
import android.os.Bundle;

public class PDFDownload extends Activity {

private static final String PDF_OUTPUT_FILENAME = "testFile.pdf";
private final String SAMPLE_URL = "http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL url = new URL(SAMPLE_URL);
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
FileOutputStream fos = openFileOutput(PDF_OUTPUT_FILENAME,
MODE_WORLD_WRITEABLE);
// Writing to file
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0){
fos.write(buf, 0, len);
fos.flush();
}
fos.close();
inputStream.close();

fos.flush();
fos.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

1 comment:

TechnoTalkative said...

Its a good site for Android example code and helpful tutorials. Keep it up.