Im trying to save a bitmap as a file however its failing for some reason
Thats the error I keep getting, it only pops up on 5.0 however I tested it on 6.0 sdk and its working fine
java.io.FileNotFoundException: /storage/sdcard/Pictures/mFile/image1491238127.jpg: open failed: EISDIR (Is a directory)
private File saveBitmap(Bitmap bitmap, String path) {
File file = null;
if (bitmap != null) {
file = new File(path);
file.mkdirs();
try {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
}
private File saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-Fashom" +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
As I observe on your code I found you creating file.mkdir(); it means you creating a new file not get u need to write the code after try catch return exception.
try {
//it gets file path
file = new File(path);
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
ting the exist file..
Related
I have created a file and written into the file using editText. Now I want to write into a file named "note.txt". But the content to be written should be stored in a variable. Can any one help me with the code??
private void writeFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Save to: " + path);
String data = editText.getText().toString();
try {
File myFile = new File(path);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Do you mean this?:
private void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try{
out = openFileOutput("note.txt",Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if (writer!=null);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How to append data one by one in existing file? Am using following code.. Append the data row order in file..How to solve this?
private String SaveText() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS");
dir.mkdirs();
String fname = "gps.txt";
File file = new File (dir, fname);
FileOutputStream fos;
try {
fos = new FileOutputStream(file,true);
OutputStreamWriter out=new OutputStreamWriter(fos);
out.write(value1);
out.close();
fos.close();
Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
return dir.getAbsolutePath();
}
Try this code
try{
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write(value1);
fbw.newLine();
fbw.close();
Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
Copy and paste this code.
public void SaveText(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}}
In JAVA 7 you can try:
try {
Files.write(Paths.get(dir+File.separator+fname), latLng.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
checkout Beautiful explanation :here
I'm using this code to save images in the SD card (simulated or real) but all the testers of my app are telling me that the have a new folder in their Photos app with all my images (I don't know why on my Nexus 4 with KK this is not happening).
static public void storeImage(Bitmap image, String imgName) {
String root = Environment.getExternalStorageDirectory().toString();
File myRoot = new File(root + "/files");
if (!myRoot.exists()) {
myRoot.mkdir();
}
File myDir = new File(root + "/images/");
if (!myDir.exists()) {
myDir.mkdir();
}
File file = new File(BasePathToFile(imgName));
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to change de visibility, security or something to avoid that the Photos App or any App get access to my folder??
After reading a lot I have found this in the android dev page.
So at the end if you want that your files remain private you have to store them in the device.
So I have change my code to this:
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(context.getFilesDir(), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I hope this will be useful to someone.
Happy coding.
A #Sebastian pointed getExternalFilesDir(String type) is a more complete solution so i have changed de code to this:
private static Boolean SdMemoryExist() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
static public String BasePath(Context context) {
String _basePathToCheck;
if (SdMemoryExist()) {
_basePathToCheck = context.getExternalFilesDir(null).toString() + File.separator;
} else {
_basePathToCheck = context.getFilesDir().toString() + File.separator;
}
return _basePathToCheck;
}
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(BasePath(context), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding.
Please help me out I am not getting the default ringtone file path.
Can any body tell how to get access to the default ringtone in Android. Here is my code for doing that thing. I have commented the path that I gave directly to asset manager to open the file and read it.
public void copyAssets() {
AssetManager assetManager = this.getAssets();
// String FileName="//media/internal/audio/media/";
File io=getFilesDir();
String[] files = null;
try {
files = assetManager.list("");
// files=assetManager.list(FileName);
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
// File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
// File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
// FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual
//
try {
in = assetManager.open("Ringtone");
// File myFolder = new File(Environment.getDataDirectory() + "/myFolder");
File myFolder = this.getDir("myFolder", this.MODE_PRIVATE);
File fileWithinMyDir=new File(myFolder,"Ringtoness");
out = new FileOutputStream(fileWithinMyDir);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
}
public void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}`
I am trying to test for this cache in my asyncTask. How would i go about doing this?
public void putBitmapInDiskCache(URI imageUri, Bitmap avatar) {
File cacheDir = new File(this.getCacheDir(), "thumbnails");
cacheDir.mkdirs();
File cacheFile = new File(cacheDir, ""+imageUri.hashCode());
try {
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
avatar.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("error", "Error when saving image to cache. ", e);
}
Based on what you have. If prior to your call to createNewFile() you were to check if it exists, you can do whatever needs to be done there
if (cacheFile.exists()) { ... } else { cacheFile.createNewFile() }