Got FileNotFoundException for Environment.getExternalStorageDirectory() - android

I know there are many post on Environment.getExternalStorageDirectory() for finding out folder for saving files. When I used it, I am getting
/storage/emulated/0/myfolder
as folder path and getting below error when try to use for saving file.
w/System.err: java.io.FileNotFoundException: /storage/emulated/0/myfolder/myfile (No such file or directory)
How to resolve this issue? I would like to use Internal Memory for storing Image & video in the same fashion as other app does.
Thanks in advance for your help.
Update : As requested Code for saving Image that is been created.
public String saveTofolder(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), "myfolder");
if (!folder.exists()) folder.mkdirs();
File file = new File(folder.getAbsoluteFile(), filename);
if (!file.exists()) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
try {
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
stored = "success";
}
return stored;
}

Related

cannot delete bitmap from external storage

I cannot seem to delete a picture from the local storage. What I want to happen is: delete the old picture, add a new picture with the same name.
When I change the picture name it has no problem loading it as a new one. But when I don't change its name it shows the old picture.
I tried context.deleteFile(filename). file.exists returns false after deletion but the picture is still there.
A solution with overwriting can be helpful.
I also have external storage permissions in the manifest.
Thanks!
The deletion:
void deleteOldPicture(String filename, Context context){
File file = new ImageSaver(context).setFileName(filename).setDirectoryName("images").createFile();
file.delete();
}
Creating the file
File createFile() {
File directory;
if(external){
directory = getAlbumStorageDir(directoryName);
}
else {
directory = context.getDir(directoryName, Context.MODE_PRIVATE);
}
return new File(directory, fileName);
}
private File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e("ImageSaver", "Directory not created");
}
return file;
}
Saving the file:
private String saveFileInSD(String name, ImageView image){
String filename = name+parentId+".png";
Log.e("Filename is", filename);
new ImageSaver(getApplicationContext()).setFileName(filename).setDirectoryName("images").save(((BitmapDrawable) image.getDrawable()).getBitmap());
return filename;
}
add this library to your Gradle, it will help clean up your code a little bit :
implementation 'org.apache.commons:commons-io:1.3.2'
the do the following to save the picture :
//Compress the Bitmap
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//save Bitmap to file and get it form preview activity and especially to avoid TransactionTooLargeException
File imageFile = new File(getExternalCacheDir(), "image.png");
try {
FileOutputStream imageFileStream = new FileOutputStream(imageFile);
IOUtils.copyLarge(new ByteArrayInputStream(stream.toByteArray()), imageFileStream);
IOUtils.closeQuietly(imageFileStream);
} catch (Exception e) {
e.printStackTrace();
}
to get the path of your saved bitmap just use the following method :
imageFile.getAbsolutePath()

Android, write image into internal memory

I have gotten this message when I try to save an imagen file ...
java.io.FileNotFoundException: /logocte1 (Read-only file system)
My method ...
public static String saveFile(Bitmap bitmap, String filename) {
String stored = null;
File file = new File(filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
I want to write the file INTO internal menory ... I don't have external memory in my pone.
I have gotten this message when I try to save an imagen file
You cannot write to arbitrary locations. Please use methods like getFilesDir() and getExternalFilesDir() for directories that you can write to.
I don't have external memory in my pone.
Most likely, you do. External storage is not the same as removable storage, and neither of those are the same as internal storage.

Save image in current view to sdcard using Android universal-image-loader

I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.

Android get image from internal/external storage

I try to show my created png file in an imageView. When I start my program and click the showCreatedPng button, there is just a white blank page on emulator's screen.
And logCat says : (Maybe Logcat shows errors because of Emulator. My emulator has 200 mb sd-card but, I can not find where is the created PNG in my computer. When I start the program my phone, PNG saved in GT-I9100\Phone folder. I guess the folder is an internal folder. Anyway, I can not see my created png file. Please help.)
05-21 21:53:39.764: E/BitmapFactory(1335): Unable to decode stream: java.io.FileNotFoundException: /mnt/sdcard/*.png: open failed: ENOENT (No such file or directory)
These are codes that I used.
For saving :
private void saveImageToExternalStorage(Bitmap bitmap) {
String qrPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
try
{
File dir = new File(qrPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(qrPath, "QRCode.png");
if(file.exists()){
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
}
catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
}
And codes for get png file :
String qrPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/*.png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap mustOpen = BitmapFactory.decodeFile(qrPath, options);
setContentView(R.layout.qr_image);
ImageView imageView = (ImageView) findViewById(R.id.qr_image);
imageView.setImageBitmap(mustOpen);
Thanks for your help.
You are trying to open a file called *.png. This should probably be QRCode.png, thus the code
Environment.getExternalStorageDirectory().getAbsolutePath() + "/QRCode.png";

Store Bitmap image to SD Card in Android

I am facing some strange problem with my android code,
I have an image in Bitmap variable and want to save that file to SD card.
I code as follow,
Bitmap IMAGE // Loaded from internet servers.;
try {
File _sdCard = Environment.getExternalStorageDirectory();
File _picDir = new File(_sdCard, "MyDirectory");
_picDir.mkdirs();
File _picFile = new File(_picDir, "MyImage.jpg");
FileOutputStream _fos = new FileOutputStream(_picFile);
IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos);
_fos.flush();
_fos.close();
Toast.makeText(this, "Image Downloaded", 7000).show();
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(this, ex.getMessage(), 7000).show();
}
I am using Sony Experia Arc as my testing device, when the phone is connected to my computer, the code works nice, it stores image and also displays in gallery. But when I disconnect phone from my computer and test the app, it doesn't save picture and doesn't show any exception.
use this function
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Check this answer will give more details Android saving file to external storage
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**This Code Cover the Following Topics**
1. Save a bitmap Image on sdcard a jpeg
2. Create a folder on sdcard
3. Create every file Separate name
4. Every file save with date and time
5. Resize the image in very small size
6. Best thing image Quality fine not effected from Resizing
The following method is used to create an image file using the bitmap
public void createImageFromBitmap(Bitmap bmp) {
FileOutputStream fileOutputStream = null;
try {
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Capture/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
//Capture is folder name and file name with date and time
fileOutputStream = new FileOutputStream(String.format(
"/sdcard/Capture/%d.jpg",
System.currentTimeMillis()));
// Here we Resize the Image ...
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream); // bm is the bitmap object
byte[] bsResized = byteArrayOutputStream.toByteArray();
fileOutputStream.write(bsResized);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources