What should i use InputStream or FileInputStream or BufferedInputStream? - java

I am downloading few pdf and video file from the server and for that I am using InputStream to collect response but I want to know that which is better for my purpose InputStream or FileInputStream or BufferedInputStream ?
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile, fileName));
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();

I am using this for downloading videos
void downloadFile(String vidN){
int downloadedSize = 0;
int totalSize = 0;
try {
// here vidN is the name of the file like bird.mp4
// here sitepath is the path of the file
URL url = new URL(sitepath+vidN);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "VideoNR2";
File RootFile = new File(RootDir);
RootFile.mkdir();
//create a new file, to save the downloaded file
File file = new File(RootDir,""+vidN);
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize = bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
}
}

Related

File download incomplete when application killed or destroy

When I am downloading a file from the server if suppose I killed or destroy the application means it will download only half of data how to resume download when application open or how to delete incomplete data in the file.
Any ideas?
private void downloadBookDetails(String pMainFolder, String pFileName, String pDownloadURL) {
Log.i(TAG, "Coming to this downloadBookDetails ");
try {
URL url = new URL(pDownloadURL);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File directory = new File(pMainFolder, pFileName);
FileOutputStream outStream = new FileOutputStream(directory);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
} catch (Exception e) {
//Add Network Error.
Log.e(TAG, "Download Error Exception " + e.getMessage());
e.printStackTrace();
}
}
You should use DownLoad Manager for downloads in your app. This will automatically handles all the things for you. Which is a system service that can handle long-running HTTP downloads.
UPDATE
If you want to download the file by your own then you can use it like below:
#SuppressLint("Wakelock")
#Override
protected String doInBackground(String... sUrl) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wl.acquire();
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/"+fileName);
int downloaded=0;
if(file.exists()){
downloaded=(int) file.length();
connection.setRequestProperty("Range", "bytes=" + (int) file.length() + "-");
}
else{
file.createNewFile();
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength()+(int)file.length();
// download the file
input = connection.getInputStream();
if(downloaded>0){
output = new FileOutputStream(file,true);
}
else{
output = new FileOutputStream(file);
}
byte data[] = new byte[1024];
long total = downloaded;
int count;
mProgressDialog.setMax(fileLength/1024);
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled())
return null;
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)total/1024);
output.write(data, 0, count);
}
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
if (connection != null)
connection.disconnect();
wl.release();
return null;
} catch (Exception e) {
return e.toString();
}
}
catch (Exception e) {
return e.toString();
}
}

Http UrlConnection Java for File Download

We have to connect to a asp.net server to download media items.
We've got this code:
URLConnection urlConnection;
try {
String localTempPath = SettingsManager.getInstance().getLocalTempMediaItemFilePath(loadingItem);
URL serverPath = new URL(SettingsManager.getInstance().getServerMediaItemFilePath(loadingItem));
urlConnection = serverPath.openConnection();
String urlParameters = "http://tempuri.org/";
HttpURLConnection connection = (HttpURLConnection) serverPath.openConnection();
connection.setFollowRedirects(true);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
for (String cookie:cookies.keySet()) {
connection.setRequestProperty("Cookie", cookie + "=" + cookies.get(cookie));
} //only one Cookie: ASPNET_SessionId=...
connection.connect();
int response = connection.getResponseCode();
File f = new File (localTempPath);
f.createNewFile();
if (f.exists()){
FileOutputStream fileOutput = new FileOutputStream(f);
//Get Response
InputStream is = connection.getInputStream();
int totalsize = connection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte [1024];
int bufferLength = 0;
while ((bufferLength = is.read(buffer)) > 0){
fileOutput.write(buffer,0,bufferLength);
downloadedSize += bufferLength;
}
fileOutput.close();
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
We have to send the Session-Cookie to the server but we always get a 404:java.io.FileNotFoundException: http://possuite.emmgt.at/v30/dataservice/MediaItem/6629.mi

Image quality very low when images fetched from Facebook and written to SD.

I am fetching images from Facebook and writing them to SD card, but the image quality is very low. Following is my code to fetch and write:
try
{
URL url = new URL(murl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
data1 = String.valueOf(String.format(getActivity().getApplicationContext().getFilesDir()+"/Rem/%d.jpg",System.currentTimeMillis()));
FileOutputStream stream = new FileOutputStream(data1);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
byte[] byteArray = outstream.toByteArray();
stream.write(byteArray);
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
The following code I use to display the same image:
File IMG_FILE = new File(IMAGE_CONTENT);
B2.setVisibility(View.INVISIBLE);
Options options = new BitmapFactory.Options();
options.inScaled = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(IMG_FILE.getAbsolutePath(),options);
iM.setImageBitmap(bitmap);
The quality is still low even after using Options. What can be done to improve this?
to Save image from URL onto SD card use this code
try
{
URL url = new URL("Enter the URL to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String filename="downloadedFile.png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath=file.getPath();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
use this code to set sdcard image as your imageview bg
File f = new File("/mnt/sdcard/photo.jpg");
ImageView imgView = (ImageView)findViewById(R.id.imageView);
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
imgView.setImageBitmap(bmp);
else use this
File file = ....
Uri uri = Uri.fromFile(file);
imgView.setImageURI(uri);
You can directly show image from web without downloading it. Please check the below function . It will show the images from the web into your image view.
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
then set image to imageview using code in your activity.
The issue is that you're dealing with a lossy format (JPG) and are re-compressing the image. Even with quality at 100 you still get loss - you just get the least amount.
Rather than decompressing to a Bitmap then re-compressing when you write it to the file, you want to download the raw bytes directly to a file.
...
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(data1);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
...

How to get the file size while it is written on the sd?

Please, help me. I need to get full file size and already writed in while loop. I need this to set progress of my progress bar.
This is my code:
try {
URL u = new URL(imgUrl);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "saved" + File.separator);
root.mkdirs();
String name = "" + System.currentTimeMillis() + ".jpg";
File sdImageMainDirectory = new File(root, name);
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
OutputStream output = new FileOutputStream(sdImageMainDirectory);
while ((length = dis.read(buffer))>0) {
output.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
If you want to get the number of bytes you already have written, use something like this:
Add a variable called writtenBytes before your while loop:
long writtenBytes = 0L;
Then, in your while loop, add the following code:
while ((length = dis.read(buffer))>0) {
output.write(buffer, 0, length);
writtenBytes += length;
}
To get the file size before downloading your file, you'll have to change your downloading code to something like:
URL url = new URL(imgUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream inputStream = url.openStream();
DataInputStream dis = new DataInputStream(is);

Java file corruption uploading via URLConnection

Im not sure why this is happening from time to time but file sizes differ when I upload to a remote ftp server.
Here is how I do this:
URLConnection uc;
try {
uc = Init.net.openConnection();
OutputStream os = uc.getOutputStream();
FileInputStream fis = new FileInputStream("List.jkm");
byte[] buffer = new byte[1024];
int count = 0;
while((count = fis.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
fis.close();
os.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
Appreciate some hints

Categories

Resources