Reading from a file in android - android

In the following code:
fileInputStream = new FileInputStream(new File(pathToOurFile) );
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Printing buffer is giving some random value, instead of what is there in file. buffersize is properly calculating the size of the file.
Can you tell wat is going wrong?

Try this..
private void ReadFile(AssetManager manager, String sourceFileName,
String destinationFileName) throws IOException {
// Read file from AccessManager
InputStream inputStream = manager.open(sourceFileName);
OutputStream outputStream = new FileOutputStream(destinationFileName);
Log.d("-->", "src: " + sourceFileName);
Log.d("-->", "Des: " + destinationFileName);
byte[] buffer = new byte[3072];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
outputStream = null;
inputStream = null;
}

Related

How to read large file to byte array?

I have tried for 200 MB of image file and converting it onto byte array but is crashed due to OOM, so how to read large file and converting into byte[]
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 210288697 byte allocation with 4108138 free bytes and 186MB until OOM
byte[] fullyReadFileToBytes(File file) throws IOException {
int size = (int) file.length();
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
FileInputStream fis = new FileInputStream(file);
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e) {
throw e;
} finally {
fis.close();
}
return bytes;
}
NOTE: I have tried for 100MB and it is working perfect but in case of size greater than 150MB it's creating crash.
Use Http post multipart transfer i.e.
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;//1 mb buffer - set size according to your need
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
Use volley multi-transfer request. It will keep track of failures
https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
The below code helps to compress the bitmap image and convert to string bytes.
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] b = baos.toByteArray();
String temp = null;
try {
System.gc();
temp = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
b = baos.toByteArray();
temp = Base64.encodeToString(b, Base64.DEFAULT);
}
return temp;
}

How to create mp4 file from bitmap arraylist in Android

I want to record a mp4 file from bitmap arraylist.My code:
File directory = intiFilePath();
DataOutputStream out = new DataOutputStream(new FileOutputStream(directory.getPath()+"/test.mp4"));
int maxBufferSize = 256 * 1024;// 256KB
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
for (Bitmap n : bmpList) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
n.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
DataInputStream in = new DataInputStream(bs);
bytesAvailable = in.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = in.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
out.write(buffer, 0, bytesRead);
out.flush();
bytesAvailable = in.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = in.read(buffer, 0, bufferSize);
}
in.close();
}
out.close();
But the mp4 file cannot play (the file is exist).
Anyone can help me what's wrong.
Sorry, but you can't. Try use OpenCv lib

Android httpURLConnection already running

I've got an app where in I was calling an httpURLConnection with the requestproperty connection "stay-alive".
Because I didn't call the HttpURLConnection.disconnect() when my app was crashing, he didn't make it to the disconnect call because I didn't put it in the finally method.
Problem
When I rerun my app, I see that my url.openConnection() already see the old HttpUrlConnection and take that back out of the pool. Problem now is that I can't simply kill the already existed connection.
After some research on the web I found an old bug report (https://code.google.com/p/android/issues/detail?id=2939)
I already tried different approaches, but after the url.openConnection() calling httpURLConnection.disconnect() didn't do anthing. Reinstall app, reboot pc and tablet also weren't effective.
Known exceptions
java.lang.IllegalStateException: Already connected
Question
So my question is: How can I kill the existed HttpURLConnection?
Here a brief example of the wrong used code:
try{
File file = new File("resources/test.png");
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlRequest);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Get Cookie from session
String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();
//allow inputs & outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//Enable GET method
connection.setRequestMethod("GET");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "MyAgent");
connection.setRequestProperty("Cookie", key+"="+value);
//Call with stream fields
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
//Call with stream
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
/*outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""+ Configuration.userTempImage.getPath()+ "\""+lineEnd);
outputStream.writeBytes(lineEnd);*/
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
//Read file
bytesRead = fileInputStream.read(buffer, 0 , bufferSize);
while(bytesRead > 0){
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
/*outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);*/
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String jsonText = readAll(rd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
System.out.print(serverResponseCode + " - " + serverResponseMessage+" -> ");
} catch (Exception ex){
System.out.print(ex.getMessage());
}
And this is my updated code
private static String getImagePath(String urlRequest){
System.setProperty("http.keepAlive", "false");
// ?
FileOutputStream fos = null;
// The connection to the server
HttpURLConnection connection = null;
// The data steam for sending the file to the server
DataOutputStream outputStream = null;
// A file stream to read the local file.
FileInputStream fileInputStream = null;
// ?
ByteArrayOutputStream stream = null;
// Cropped image file
File croppedImage = null;
try{
try{
stream = new ByteArrayOutputStream();
Configuration.userTempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// Close the output-stream
if(stream != null) { stream.close(); }
croppedImage = new File(Environment.getExternalStorageDirectory(), "test.jpg");
if(croppedImage.exists()){
croppedImage.delete();
}
fos = new FileOutputStream(croppedImage);
fos.write(byteArray);
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
} finally {
if(fos != null) { fos.close(); }
}
//Get Cookie from session
String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();
URL url = new URL(urlRequest);
connection = (HttpURLConnection)url.openConnection();
//Allow inputs & outputs
connection.setDoInput(true); // <-- Exception is thrown here
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set connection properties
connection.setRequestProperty("Cookie", key+"="+value);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "MyAgent");
// Set connection headers
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
//Call with stream fields
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
// Create an input stream to the cropped image file
fileInputStream = new FileInputStream(croppedImage);
// Create an output stream to send the file to the server
outputStream = new DataOutputStream(connection.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
//Read file
bytesRead = fileInputStream.read(buffer, 0 , bufferSize);
while(bytesRead > 0){
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// Be sure to send everything
outputStream.flush();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String jsonText = RequestHelper.readAll(rd);
return jsonText;
}catch(Exception ex){
ex.printStackTrace();
} finally {
try{
if(fileInputStream != null) { fileInputStream.close(); }
if(outputStream != null) { outputStream.close(); }
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(connection != null) { connection.disconnect(); }
}
}
return null;
}

Android : How to determine the file extension of a file

I am trying to share files between two Android phones using Socket programming. The problem is right now I have to hard code the file extension on the receiving end. Is there a way that I can automatically determine the extension of the file being received?
Here's my code.
Client Side
socket = new Socket(IP,4445);
File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = null;
fis = new FileInputStream(myFile);
OutputStream os = null;
os = socket.getOutputStream();
int filesize = (int) myFile.length();
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
socket.close();
}
And the Server side
FileOutputStream fos = null;
File root = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(root,"B.jpg")); //Here I have to hardcode B.jpg with jpg extension.
BufferedOutputStream bos = new BufferedOutputStream(fos);
ServerS = new ServerSocket(4445);
clientSocket = ServerS.accept();
InputStream is = null;
is = clientSocket.getInputStream();
int bytesRead = 0;
int current = 0;
byte [] mybytearray = new byte [329];
do {
bos.write(mybytearray,0,bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
} while(bytesRead > -1);
bos.flush();
bos.close();
clientSocket.close();
}
You can find the file extension pretty easily by doing this:
String extension = filename.substring(filename.lastIndexOf('.'));

uploading video upto 50MB to the server

I want upload videos from my android apps to server.When iam trying to upload the video my apps shows04-23 13:07:41.602: ERROR/dalvikvm-heap(519): Out of memory on a 15607356-byte allocation.I dont know why the error is occuring.My question is
Can we upload video of size upto 50MB using the below code?if anybody knows please help me...
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 8*1024*1024;
Cursor c = (MainscreenActivity.JEEMAHWDroidDB).query((MainscreenActivity.TABLE_Name), new String[] {
(MainscreenActivity.COL_HwdXml)}, null, null, null, null,
null);
if(c.getCount()!=0){
c.moveToLast();
for(int i=c.getCount()-1; i>=0; i--) {
value=c.getString(0);
}
}
String urlString = value+"/upload_file.php";
try
{
//------------------ CLIENT REQUEST
UUID uniqueKey = UUID.randomUUID();
fname = uniqueKey.toString();
Log.e("UNIQUE NAME",fname);
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fname + "."+extension+"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
System.out.println("BYTES:--------->"+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
System.out.println("BUFFER SIZE:--------->"+bufferSize);
buffer = new byte[bufferSize];
System.out.println("BUFFER:--------->"+buffer);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
System.out.println("BYTES READ:--------->"+bytesRead);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("RETURNED");
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
try replacing
bytesAvailable = fileInputStream.available();
System.out.println("BYTES:--------->"+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
System.out.println("BUFFER SIZE:--------->"+bufferSize);
buffer = new byte[bufferSize];
System.out.println("BUFFER:--------->"+buffer);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
System.out.println("BYTES READ:--------->"+bytesRead);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("RETURNED");
}
with
buffer = new byte[8192];
bytesRead = 0;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dos.write(buf, 0, bytesRead);
}
Explained: read() will return you the number of bytes it read or -1 if the end of the stream is reached and no further data can be read. It also fills the first N bytes of buffer with the data it read. The (a = b) != c syntax first assigns b to a, then compares the value to c (here: execute read, assign result to bytesRead, compare to -1). Therefore the loop runs until every byte is read from start to the end of the stream.
After each read the data in buffer is written via write. Since we know from bytesRead how much bytes in buffer are actually newly read bytes we tell write to write only the bytes from 0 to bytesRead. No need to check InputStream.available() (which may even return meaningless results if the length of the stream is not known) or any other method.
Note: changing that to while (bytesRead > 0) introduces a subtle difference. It will stop reading if you read 0 bytes but did not reach the end of the stream. That case is legal although it is pretty safe to assume that it does not happen. You are safer if you use bytesRead >= 0 though.
That means, you run out of memory. Try to reduce your my memory usage by decreasing buffer size:
int maxBufferSize = 2*1024*1024;
even after using this code you will have same error "out of memory" in this case you should use httppost and multipart entity to post your data...

Categories

Resources