This question already has an answer here:
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 4 years ago.
I'm trying to convert a File to byte array format. The selected actual path is there in the storage, but still its throwing exception as "File Not Found". Can anyone help me to sort out this?
Thanks for your precious time!..
calling file manager
btn_click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
});
getting response
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String filePath = data.getData().getPath();
System.out.println("====== path : "+filePath);
File file = new File(filePath);
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
System.out.println("====== bytesArray "+bytesArray);
} catch (FileNotFoundException e) {
System.out.println("====== File Not Found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("====== Error Reading The File. IOException");
e.printStackTrace();
}
}
}
}
Add the following grade its Apache commons gradle
compile 'org.apache.commons:commons-io:1.3.2'
then use this code
byteArray = FileUtils.readFileToByteArray(file);
Related
I want to create a file in AppA and then be able to access it from AppB only. I am able to create the file via the DocumentProvider and then access it via StorageClient see examples here. How do I setup the permission on the file in AppA so that only AppB can access it?
Method for file creation in AppA
String s = "kv;ab\nkv1;cd";
try {
byte[] buffer = s.getBytes();
String filename = "myfile.txt";
System.out.println("filename="+filename);
FileOutputStream fos = getContext().openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
Methods for File access in AppB
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
Uri pickerInitialUri= Uri.parse("content://com.example.android.storageprovider.documents/document/root%3Amyfile.txt");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, READ_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
readFileExternalStorage();
}
public String readFileExternalStorage() {
String s = "";
Uri uri1 = Uri.parse("content://com.example.android.storageprovider.documents/document/root%3Amyfile.txt");
try {
InputStream ins = this.getBaseContext().getContentResolver().openInputStream(uri1);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int size;
byte[] buffer = new byte[1024];
while ((size = ins.read(buffer, 0, 1024)) >= 0) {
outputStream.write(buffer, 0, size);
}
ins.close();
buffer = outputStream.toByteArray();
s = new String(buffer);
System.out.println("output=" + s);
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
TextView textview = findViewById(R.id.textView);
textview.setText(s);
return "ok\n" + s;
}
Two probable options-
https://developer.android.com/guide/topics/permissions/defining
Use a shared encryption key with user based salt to encrypt and decrypt stored files on Android
i am trying to pick an audio file and save it , but i am getting ENOENT , yet i use the same code with image and it works fine !!!!! \n
i am using file provider to create/save files and it works more than probably .
how can the same code work with images yet not with audio : \n
here is some code examples \n
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == RESULT_OK) {
Uri resultUri = data.getData();
saveFile(resultUri);
}
}
and to save the file i use :
File dirPath = new File(Environment.getExternalStorageDirectory(),"Moch/WAR/");
File file = new File(dirPath, "notification.mp3");
String sourceFilename = resultUri.getPath();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
if(!file.exists())
if (!file.createNewFile())
Toast.makeText(notificationsSettings.this,"Unable to make sound File",Toast.LENGTH_LONG).show();
if(file.exists()) {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(file, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
mProgressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is the doomed error line : \n
/document/audio:266: open failed: ENOENT (No such file or directory)
i am trying to copy whole directory to usb storage :
File Sdfile = new File(Environment.getExternalStorageDirectory(), "myfolder");
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.setType("*/*");
intent.setType(DocumentsContract.Document.MIME_TYPE_DIR);//For API 19+
intent.putExtra(Intent.EXTRA_TITLE, Sdfile.getName());
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 47);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 47) {
if (resultCode != RESULT_OK) return;
File file = new File(Environment.getExternalStorageDirectory(), "myfolder");
copyFile(file, data.getData());
}
Below code is for copy the whole folder to usb storage.
private void copyFile(File src, Uri destUri) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
byte[] buf = new byte[5024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
when i am trying to copy the whole folder then it gives error.
Even i direct copy the whole folder to usb storage .
How can i copy whole directory ?
I'm guessing your app does not have the correct permissions. For Android versions below KitKat, you need to declare the permission WRITE_EXTERNAL_STORAGE in your AndroidManifest.xml
<user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Reference: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE
I am trying to use getCropAndSetWallpaperIntent method of WallpaperManager class, but face problems with uri it need. First I tried to get Uri from drawable resourse, but I concluded that this is impossible, and decided to write file to internal storage and get its Uri. Now it gives an error, that uri type must be content. How can I fix this error? Maybe writing file to memory is totally wrong and there are other solutions?
Here is my code:
public void onclick(View v){
switch (v.getId())
{
case R.id.set:
// try{
//R.drawable.file1
File file =new File(this.getFilesDir(),getResources().getResourceName(R.drawable.file1));
file.setWritable(true);
if (!file.exists())
{
Bitmap bm= BitmapFactory.decodeResource(getResources(),R.drawable.file1);
try {
FileOutputStream outputStream=new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Uri uri=Uri.fromFile(file);
Intent i=wmanager.getCropAndSetWallpaperIntent(uri);
startActivity(i);
break;
case R.id.clear:
try{
wmanager.clear();
}
catch (IOException ioex){
ioex.printStackTrace();
}
}
}
I have seen the same problem, fixed by following method and works fine.
#TargetApi(Build.VERSION_CODES.KITKAT) private void setWallpaperKitkat(File file) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(WallpaperManager.ACTION_CROP_AND_SET_WALLPAPER);
String mime = "image/*";
intent.setDataAndType(uri, mime);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
//handle error
}
}
I'm trying to implement a simple file upload and associate the file with the current user.
I followed the guide on parse.com and checked with several questions on here with no luck.
The saveinBackground operation is successful, no exceptions are being thrown but I can't see the file in Parse.com data browser.
Here's my code.
final long time1 = Time;
//Image part
//upload the .jpg file for user's history
//Parse
byte[] data = filePath.getBytes();
final ParseFile file = new ParseFile("asdasd.jpg", data);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// Handle success or failure here ...
if ( e == null){
ParseObject rentedTime = new ParseObject("Time");
rentedTime.put("duration", renttime1);
rentedTime.put("owner", ParseUser.getCurrentUser());
rentedTime.put("id", id);
rentedTime.put("image", file);
rentedTime.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null)
Log.d("upload successful" + file.getName(), null);
}
});
} else {
Log.d("terrible", e.getMessage());
}
}
}, new ProgressCallback() {
public void done(Integer percentDone) {
// Update your progress spinner here. percentDone will be between 0 and 100.
}
});
}
What am I missing?
That's because you are NOT uploading the file..see
byte[] data = filePath.getBytes();
just getting the bytes from the file path wont work reasonably.
First get the bitmap and then convert it to byte[] see how..
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
byte[] data = getBytes(bitmap);
private byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] data = outputStream.toByteArray();
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
And you can now use the data..
final ParseFile file = new ParseFile("asdasd.png", data);
I've changed the file name to .png format if you wish ti save in jpg format then compress in .JPG format as well.
Hope you find this helpful! :)