I'm using a content provider with an overridden openFile method:
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
ParcelFileDescriptor[] pipe = null;
InputStream in = null;
try {
pipe = ParcelFileDescriptor.createPipe();
String path = uri.getPath();
in = new FileInputStream(new File(path));
PipeFeederThread p = new PipeFeederThread(in, new AutoCloseOutputStream(pipe[1]));
p.start();
/*catches.... */
return (pipe[0]);
}
PipeFeederThread contains the usual block-write procedure:
byte[] buf = new byte[8192];
int len;
try {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
Log.i("WRITE","Writing...");
}
Log.i("WRITE","Finished");
in.close();
out.flush();
out.close();
} catch (Exception e) {
}
But when I try to use my provider with an ACTION_VIEW intent like the gallery, the provider only writes 65535 bytes to "out" (the log shows only 8 times) and then nothing happens.
I've made a counter int to break the while loop when we reach the 65535 "limit" but then it'll transfer a corrupted file.
You should use the ParcelFileDescriptor.open() method. Something like this:
private val File.assetFileDescriptor get() = AssetFileDescriptor(ParcelFileDescriptor.open(this, MODE_READ_ONLY), 0, length())
And then in your code simply do:
return in.assetFileDescriptor
Related
I‘m new to Android programming and couldn‘t find a good solution for my problem yet. In my App users can select photos from their gallery which are then used in a Cardview Layout for different categorys in the App which the user can create on his own. By now I‘m able to get Uri of the selected photo and can display it. But how can I save the photo to my App to make sure it‘s always there even though it gets deleted from the gallery?
Ref: How to make a copy of a file in android?
To copy a file and save it to your destination path you can use the method below.
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
On API 19+ you can use Java Automatic Resource Management:
public static void copy(File src, File dst) throws IOException {
t
ry (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
I'm new at android development and I'm creating simple bluetooth app that can receive xml file and save xml file values to database. But how can I receive xml file from bytes array? Is it possible? After searchinf I found this question and based ont that question I try to save byte array to file. But how I need to test it? I can't find my file in my phone.
case Constants.MESSAGE_READ:
byte[] readBuffer = (byte[]) msg.obj;
try {
String path = activity.getFilesDir() + "/myFile.xml";
Log.d("MuTestClass", path);
FileOutputStream stream = new FileOutputStream(path);
stream.write(readBuffer);
stream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
You can use:
class Utils{
public static InputStream openFile(String filename) throws IOException{
AssetManager assManager = getApplicationContext().getAssets();
InputStream is = null;
is = assManager.open(filename);
return new BufferedInputStream(is);
}
public static byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
like this:
try {
Utils.readBytes(Utils.openFile("something.xml"));
} catch (IOException e) {
e.printStackTrace();
}
I have cheerapp.wav or cheerapp.mp3 or some other format.
InputStream in = context.getResources().openRawResource(R.raw.cheerapp);
BufferedInputStream bis = new BufferedInputStream(in, 8000);
// Create a DataInputStream to read the audio data from the saved file
DataInputStream dis = new DataInputStream(bis);
byte[] music = null;
music = new byte[??];
int i = 0; // Read the file into the "music" array
while (dis.available() > 0) {
// dis.read(music[i]); // This assignment does not reverse the order
music[i]=dis.readByte();
i++;
}
dis.close();
For the music byte array which takes the data from the DataInputStream. I don't know what the length of that to allocate.
This is raw file from resource not a file therefore I wouldn't know the size of that thing.
You do have byte array length as you can see:
InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];
And then you can read whole Stream into byte array easily.
Of course I would recommend that you do check when it comes to the size and use ByteArrayOutputStream with smaller byte[] buffer if needed:
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
If you'll be doing lots of IO operations I recommend that you make use of org.apache.commons.io.IOUtils. That way you won't need to worry too much about quality of your IO implementation and once you import JAR into your project you would just do:
byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));
Hope it will help.
Create an sdcard path:
String outputFile =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
Convert as a file and have to call the byte array method:
byte[] soundBytes;
try {
InputStream inputStream =
getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));
soundBytes = new byte[inputStream.available()];
soundBytes = toByteArray(inputStream);
Toast.makeText(this, "Recordin Finished"+ " " + soundBytes, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
method:
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
In Kotlin use
InputStream.readBytes()
I am retrieveing an XML feed from a url and then parsing it. What I need to do is also store that internally to the phone so that when there is no internet connection it can parse the saved option rather than the live one.
The problem I am facing is that I can create the url object, use getInputStream to get the contents, but it will not let me save it.
URL url = null;
InputStream inputStreamReader = null;
XmlPullParser xpp = null;
url = new URL("http://*********");
inputStreamReader = getInputStream(url);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFileAppeal.srl"));
//--------------------------------------------------------
//This line is where it is erroring.
//--------------------------------------------------------
out.writeObject( inputStreamReader );
//--------------------------------------------------------
out.close();
Any ideas how I can go about saving the input stream so I can load it later.
Cheers
Here it is, input is your inputStream. Then use same File (name) and FileInputStream to read the data in future.
try {
File file = new File(getCacheDir(), "cacheFileAppeal.srl");
try (OutputStream output = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
}
} finally {
input.close();
}
Simple Function
Try this simple function to neatly wrap it up in:
// Copy an InputStream to a File.
//
private void copyInputStreamToFile(InputStream in, File file) {
OutputStream out = null;
try {
out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Ensure that the InputStreams are closed even if there's an exception.
try {
if ( out != null ) {
out.close();
}
// If you want to close the "in" InputStream yourself then remove this
// from here but ensure that you close it yourself eventually.
in.close();
}
catch ( IOException e ) {
e.printStackTrace();
}
}
}
Thanks to Jordan LaPrise and his answer.
Kotlin version (tested and no library needed):
fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(4 * 1024) // buffer size
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
We take advantage of use function which will automatically close both streams at the end.
The streams are closed down correctly even in case an exception occurs.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html
https://kotlinlang.org/docs/tutorials/kotlin-for-py/scoped-resource-usage.html
A shorter version:
OutputStream out = new FileOutputStream(file);
fos.write(IOUtils.read(in));
out.close();
in.close();
Here is a solution which handles all the Exceptions and is based on the previous answers:
void writeStreamToFile(InputStream input, File file) {
try {
try (OutputStream output = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In your application's build.gradle file add under dependencies:
implementation 'commons-io:commons-io:2.5'
In your code:
import org.apache.commons.io.FileUtils;
// given you have a stream, e.g.
InputStream inputStream = getContext().getContentResolver().openInputStream(uri);
// you can now write it to a file with
FileUtils.copyToFile(inputStream, new File("myfile.txt"));
There's the way of IOUtils:
copy(InputStream input, OutputStream output)
The code of it is similar to this :
public static long copyStream(InputStream input, OutputStream output) throws IOException {
long count = 0L;
byte[] buffer = new byte[4096];
for (int n; -1 != (n = input.read(buffer)); count += (long) n)
output.write(buffer, 0, n);
return count;
}
You can using Google Guava
import com.google.common.io.ByteStreams;
Code:
try (FileOutputStream fos = new FileOutputStream(new File("C:\\example.txt"))){
ByteStreams.copy(inputStream, fos)
}
Modern Kotlin way
fun File.copyInputStreamToFile(inputStream: InputStream?) {
outputStream().use { fileOut ->
inputStream?.copyTo(fileOut)
}
}
// Sample of usage
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
data?.data?.let { uri ->
val inputStream = contentResolver.openInputStream(uri)
val file = File(cacheDir, "todo_filename.jpg")
file.copyInputStreamToFile(inputStream)
}
}
I currently have two activities. One for pulling the image from the SD card and one for Bluetooth connection.
I have utilized a Bundle to transfer the Uri of the image from activity 1.
Now what i wish to do is get that Uri in the Bluetooth activity to and convert it into a transmittable state via Byte Arrays i have seen some examples but i can't seem to get them to work for my code!!
Bundle goTobluetooth = getIntent().getExtras();
test = goTobluetooth.getString("ImageUri");
is what i have to pull it across. What would be the next step?
From Uri to get byte[] I do the following things,
InputStream iStream = getContentResolver().openInputStream(uri);
byte[] inputData = getBytes(iStream);
and the getBytes(InputStream) method is:
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Kotlin is very concise here:
#Throws(IOException::class)
private fun readBytes(context: Context, uri: Uri): ByteArray? =
context.contentResolver.openInputStream(uri)?.buffered()?.use { it.readBytes() }
Kotlin has convenient extension functions for InputStream like buffered,use , and readBytes.
buffered decorates the input stream as BufferedInputStream
use handles closing the stream
readBytes does the main job of reading the stream and writing into a byte array
Error cases:
IOException can occur during the process (like in Java)
openInputStream can return null. If you call the method in Java you can easily oversee this. Think about how you want to handle this case.
Syntax in kotlin
val inputData = contentResolver.openInputStream(uri)?.readBytes()
Java best practice: never forget to close every stream you open!
This is my implementation:
/**
* get bytes array from Uri.
*
* #param context current context.
* #param uri uri fo the file to read.
* #return a bytes array.
* #throws IOException
*/
public static byte[] getBytes(Context context, Uri uri) throws IOException {
InputStream iStream = context.getContentResolver().openInputStream(uri);
try {
return getBytes(iStream);
} finally {
// close the stream
try {
iStream.close();
} catch (IOException ignored) { /* do nothing */ }
}
}
/**
* get bytes from input stream.
*
* #param inputStream inputStream.
* #return byte array read from the inputStream.
* #throws IOException
*/
public static byte[] getBytes(InputStream inputStream) throws IOException {
byte[] bytesResult = null;
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
bytesResult = byteBuffer.toByteArray();
} finally {
// close the stream
try{ byteBuffer.close(); } catch (IOException ignored){ /* do nothing */ }
}
return bytesResult;
}
use getContentResolver().openInputStream(uri) to get an InputStream from a URI. and then read the data from inputstream convert the data into byte[] from that inputstream
Try with following code
public byte[] readBytes(Uri uri) throws IOException {
// this dynamically extends to take the bytes you read
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
Refer this LINKs
This code works for me
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
finish();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
public void uriToByteArray(String uri)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buf = new byte[1024];
int n;
try {
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = baos.toByteArray();
}
Use the following method to create a bytesArray from a URI in Android studio.
public byte[] getBytesArrayFromURI(Uri uri) {
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}catch(Exception e) {
Log.d("exception", "Oops! Something went wrong.");
}
return null;
}