Convert a BufferedInputStream to a File - android

I am loading a image from the web to the local android phone. The code that I have for writing to a file is as follows
BufferedInputStream bisMBImage=null;
InputStream isImage = null;
URL urlImage = null;
URLConnection urlImageCon = null;
try
{
urlImage = new URL(imageURL); //you can write here any link
urlImageCon = urlImage.openConnection();
isImage = urlImageCon.getInputStream();
bisMBImage = new BufferedInputStream(isImage);
int dotPos = imageURL.lastIndexOf(".");
if (dotPos > 0 )
{
imageExt = imageURL.substring(dotPos,imageURL.length());
}
imageFileName = PATH + "t1" + imageExt;
File file = new File(imageFileName);
if (file.exists())
{
file.delete();
Log.d("FD",imageFileName + " deleted");
}
ByteArrayBuffer baf = new ByteArrayBuffer(255);
Log.d("IMAGEWRITE", "Start to write image to Disk");
int current = 0;
try
{
while ((current = bisMBImage.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("IMAGEWRITE", "Image write to Disk done");
}
catch (IOException e)
{
e.printStackTrace();
}
isImage.close();
}
catch (IOException e)
{
Log.d("DownloadImage", "Error: " + e);
}
finally
{
isImage = null;
urlImageCon = null;
urlImage = null;
}
For some reason the whole writing to a file takes 1 minute. Is there a way I can optimize this ?

Your buffer is very small: 255 bytes. You could make it 1024 times bigger (255 kilobytes). This is an acceptable size and this would certainly speed up the thing.
Also, this is very slow as it reads the bytes one by one:
while ((current = bisMBImage.read()) != -1) {
baf.append((byte) current);
}
You should try using the array version of read() instead: read(byte[] buffer, int offset, int byteCount) with an array as large as what I have described above.

You should use the Android HttpClient for file fetching over the java URL Connection. Also your Buffer is very small.
Try this snipped:
FileOutputStream f = new FileOutputStream(new File(root,"yourfile.dat"));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = is.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();

Related

Send list of files using socket wifip2p

I'm trying to send multiple files from client to server using socket but when I click upload button it adds only one file second
Your copyFile() is not suitable for network transmissions.
You need to get rid of the two close() calls inside of copyFile(). On the client side, out.close() is closing the socket after the 1st file has been sent. On the server side, InputStream.close() is closing the socket after the 1st file has been received. It is the caller's responsibility to close the streams it passes to copyFile(), it is not copyFile()'s responsibility.
More importantly, for each file the client wants to send, copyFile() is not sending the file's byte count before sending the file's actual bytes, to indicate where each file ends and the next begins. So, on the server side, copyFile() does not know when to stop reading from the inputStream and will just keep reading endlessly until the connection is closed/broken.
As-is, copyFile() may work for copying files from one folder to another on the local system, but it is not suitable for copying files over a TCP network.
Try this instead:
Client side:
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(TAG, "Client socket - " + socket.isConnected());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(fileUri.size());
for(String file : fileUri)
{
//long length = file.length();
//dos.writeLong(length);
String name = file;
dos.writeUTF(name);
File f = new File(file);
sendFile(f, dos);
}
dos.close();
Log.d(TAG, "Client: Data written");
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
}
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
}
catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
void sendFile(File in, DataOutputStream out) throws IOException {
long fileLength = in.length();
out.writeLong(fileLength);
FileInputStream fis = new FileInputStream(in);
BufferedInputStream bis = new BufferedInputStream(fis);
byte buf[] = new byte[1024];
int len;
while (fileLength > 0) {
len = bis.read(buf);
if (len == -1) throw new IOException();
out.write(buf, 0, len);
fileLength -= len;
}
}
Server side:
try {
ServerSocket serverSocket = new ServerSocket(8988);
Socket client = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
Log.d(TAG, "doInBackground: " + filesCount);
//long fileLength = dis.readLong();
String fileName = dis.readUTF();
files[i] = new File(context.getExternalFilesDir("received"), Long.toString(System.currentTimeMillis()) + ".mp4" );
Log.d(TAG, "doInBackground: 1" );
File dirs = new File(context.getPackageName() + files[i].getParent());
Log.d(TAG, "doInBackground: 2" );
if (!dirs.exists()) dirs.mkdirs();
files[i].createNewFile();
Log.d(TAG, "server: copying files " + files[i].toString());
receiveFile(dis, files[i]);
}
serverSocket.close();
return "done";
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
return null;
}
void receiveFile(DataInputStream in, File out) throws IOException {
long fileLength = in.readLong();
FileOutputStream fos = new FileOutputStream(out);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[1024];
int len;
while (fileLength > 0) {
len = (fileLength >= 1024) ? 1024 : (int) fileLength;
len = in.read(buf, 0, len);
if (len == -1) throw new IOException();
bos.write(buf, 0, len);
fileLength -= len;
}
}

How to programatically download files with increased speed in android

Hi have implemented programatically downloading of file using inputstream and cipheroutputstream(for encryption). The download is happening very slow. Whereas if i try to download via download manager, it is very fast. What can i do to improve my code and increase the download speed of the file. Below is my code.
private void saveFileUsingEncryption(String aMineType, long length) throws Exception {
int bufferSize = 1024*4;
//byte[] buffer = new byte[1024];
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long totalRead = 0;
FileOutputStream outStream = null;
File f = new File(Constants.DWLPATH);
if (!f.exists()) {
f.mkdirs();
}
try {
Cipher aes = Cipher.getInstance("ARC4");
aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec("mykey".getBytes(), "ARC4"));
if(contDisp==null || contDisp.length()==0) {
// downloadFileName = downloadFileName.replaceAll("[^a-zA-Z0-9_]+", "");
downloadFileName = downloadFileName + "." + getFileExtension(aMineType);
}
outStream = new FileOutputStream(Constants.DWLPATH + downloadFileName,true);
CipherOutputStream out = new CipherOutputStream(outStream, aes);
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) >= 0) {
out.write(buffer, 0, bytesRead);
try{
// Adjust this value. It shouldn't be too small.
Thread.sleep(50);
}catch (InterruptedException e){
TraceUtils.logException(e);
}
totalRead += bytesRead;
sb=sb.append("\n Total bytes Read:"+totalRead);
Log.e("--",sb.toString());
/* if (this.length > 0) {
Long[] progress = new Long[5];
progress[0] = (long) ((double) totalRead / (double) this.length * 100.0);
publishProgress(progress);
}*/
if (this.isCancelled()) {
if (conn != null)
conn.disconnect();
conn = null;
break;
}
}
Log.e("Download completed","success");
out.flush();
//Utils.putDownloadLogs(requestUrl,mimeType,length, downloadFileName,"Download is Successful",sb.toString(), context);
outStream.close();
buffer = null;
} catch (Exception e) {
TraceUtils.logException( e);
file_newsize = storedFileSizeInDB + totalRead;
if (totalFileSize == 0)
totalFileSize = length;
callback.onRequestInterrupted(file_newsize,totalFileSize);
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
// Utils.putDownloadLogs(requestUrl,mimeType,length,downloadFileName,"failure---" + errors.toString(),sb.toString(), context);
throw e;
} finally {
if (outStream != null)
outStream.close();
outStream = null;
}
}
You can use default download manager to download the file because its very easy to implement and provide better features like respond to the internet connection , provide accessibility to add notification in status bar , by running the query on download manager object you can find the total bytes and remaining bytes so you can calculate the progress and after completion of download by tapping the notification one can perform the desired operation.
And also there are many libraries are available for to achieve this like
PRDOWNLOADER
FetchDownloader
This libraires provide you the feature of pause,download, resume download , tracking the progress and cancel download
Also you can customize it as per your need.
Here is the DownloadAndEncryptFileTask.class to download with encryption
public class DownloadAndEncryptFileTask extends AsyncTask<Void, Void, Void> {
private String mUrl;
private File mFile;
private Cipher mCipher;
InputStream inputStream;
FileOutputStream fileOutputStream;
CipherOutputStream cipherOutputStream;
public DownloadAndEncryptFileTask(String url, File file, Cipher cipher) {
if (url == null || url.isEmpty()) {
throw new IllegalArgumentException("You need to supply a url to a clear MP4 file to download and encrypt, or modify the code to use a local encrypted mp4");
}
mUrl = url;
mFile = file;
mCipher = cipher;
}
private void downloadAndEncrypt() throws Exception {
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (mFile.length() > 0) {
connection.setRequestProperty("Range", "bytes=" + mFile.length() + "-");
}
connection.connect();
Log.e("length", mFile.length() + "");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("server error: " + connection.getResponseCode() + ", " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
if (mFile.length() > 0) {
//connection.connect();
fileOutputStream = new FileOutputStream(mFile, true);
} else {
fileOutputStream = new FileOutputStream(mFile);
}
CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, mCipher);
byte buffer[] = new byte[1024 * 1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
Log.d(getClass().getCanonicalName(), "reading from http...");
cipherOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
cipherOutputStream.close();
connection.disconnect();
}
#Override
protected Void doInBackground(Void... params) {
try {
downloadAndEncrypt();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.d(getClass().getCanonicalName(), "done");
}
}
Call this class
new DownloadAndEncryptFileTask(
myFeedsModel.getVideo().getVideo360(),
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), myFeedsModel.getFile_name()),
OBJECT OF YOUR CIPHER

save image in android

This is a code for saving images in SD card if and if not exist.
but i don't know how to read it.
Can anybody help me please.
This is the download file method:
public static String DownLoadFile(String netUrl, String name ) {
try {
//need uses permission WRITE_EXTERNAL_STORAGE
ByteArrayBuffer baf = null;
long startTime = 0;
//get to directory (a File object) from SD Card
File savePath=new File(Environment.getExternalStorageDirectory().getPath()+"/postImages/");
String ext="jpg";
URL url = new URL(netUrl);
//create your specific file for image storage:
File file = new File(savePath, name + "." + ext);
boolean success = true;
if (!savePath.exists()) {
success = savePath.mkdir();
}
if (success) {
if(file.createNewFile())
{
file.createNewFile();
//write the Bitmap
Log.i("file existence", "file does not exist!!!!!!!!!!!");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
startTime = System.currentTimeMillis();
baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
return file.getAbsolutePath();
}//end of create file if not exists
}//end of if success
} catch (Exception exx) {
if (exx.getMessage() != null) {
} else {
}
}
return null;
}
Try this,
Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
img.setImageURI(uri);
if u have image uri so get path from uri like
String Path = fileUri.getPath();
// read file from sdcard
public static byte[] readFromStream(String path) throws Exception { File
file = new File(path); InputStream inputStream = new
FileInputStream(file); ByteArrayOutputStream baos = new
ByteArrayOutputStream(); DataOutputStream dos = new
DataOutputStream(baos); byte[] data = new byte[(int) file.length()]; int
count = inputStream.read(data); while (count != -1) { dos.write(data, 0,
count); count = inputStream.read(data); } return baos.toByteArray(); }

Download takes just too much time

I'm trying to download a file in my app, but the download times are inconsistently too long.
Sometimes it just downloading it in normal time, but sometimes it just stuck for like 30 seconds or more until it will just fail due to time out error.
Why would that be?
private void Download(String url, String destFileName) throws IOException{
//TODO remove that
// File file = new File(destFileName);
// if(file.exists())
// return;
if(BuildConfig.DEBUG)
Log.d("DownloadFile", "Downloading url: " + url + ", dest: " + destFileName);
HttpGet httppost = null;
AndroidHttpClient client = AndroidHttpClient.newInstance("TvinciAndroid");
FileOutputStream fos = new FileOutputStream(destFileName);
try {
httppost = new HttpGet(url);
HttpResponse res = client.execute(httppost);
if (res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Header[] headers = res.getHeaders("Location");
if(headers != null && headers.length != 0) {
url = headers[headers.length - 1].getValue();
Download(url, destFileName);
}
}
HttpEntity responseEntity = res.getEntity();
if (responseEntity != null && responseEntity.getContentLength() > 0) {
InputStream is = AndroidHttpClient.getUngzippedContent(responseEntity);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,Charset.forName("UTF-8")));
StringBuilder bld = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
line += "\n";
fos.write(line.getBytes());
bld.append(line);
}
reader.close();
if(BuildConfig.DEBUG)
Log.d("file content", bld.toString());
bld = null;
}
}
catch(IOException ex){
throw ex;
}
finally {
client.close();
fos.close();
}
}
Any help will be much appreciated
Try specifying the buffer to 8192.
//input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
I have a sample working code here that can download a file via URL It is different from your implementation, but this might help you.
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
// getting file length
int lengthOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(filePath);
byte data[] = new byte[1024];
long total = 0;
pDialog.setMax(lengthOfFile);
NOTIFICATION_ID = 1+lengthOfFile;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
//publishProgress(""+(int)((total*100)/lenghtOfFile));
publishProgress(""+(int)(total));
notifBuilder.setProgress(lengthOfFile, (int)(total), false)
.setContentText("Download in progress... "+total+"/"+lengthOfFile);
nm.notify(NOTIFICATION_ID, notifBuilder.build());
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("Error: ", e.getMessage());
return e.getMessage()+" download failed!";
}
I Hope this helps.

Download image(SSL) and store it on SDcard in Android?

I need to download a single image at time from the Internet and then save it on the SD card. How do I do it? I have made an attempt, but when I try to view that downloaded image, it shows the message, "No Preview Available". Please see my code below:
public class ImgDownloader {
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static final byte[] downloadImage(String imgURL) {
byte[] data = null;
try {
Log.v("Down", "1");
InputStream in = null;
BufferedOutputStream out = null;
in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024);
Log.v("Down", "2");
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
Log.v("Down", "3");
data = dataStream.toByteArray();
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.v("Down", "4");
} catch (Exception ex) {
ex.printStackTrace();
// System.out.println("Exception in Image Downloader .."
// +ex.getMessage());
}
return data;
}
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
Note:
i have download the image from the SSL connection.
Any ideas? Thanks in advance.
You can try something like
try{
URL url = new URL(downloadUrl); //you can write here any link
File file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
//Create parent directory if it doesn't exists
if(!new File(file.getParent()).exists())
{
System.out.println("Path is created " + new File(file.getParent()).mkdirs());
}
file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
file.createNewFile();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = is.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
Make the appropriate changes according to your requirement. I use the same code for downloading files from internet and saving it to SDCard.
Hope it helps !!

Categories

Resources