How to save a file to a specific spot on the phone - java

I would like for my app to create a folder on the sd card and save a file in it. This is what I have right now that just saves it in my app data.
File file = new File(context.getExternalFilesDir(""), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
How would I do that?
Alright so I did this. Am I even doing this right?
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "";
File file = new File(fullPath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}

Your best option is to use Environment.getExternalStorageDirectory() to find the root path to use.
However, please note that this is not nessasarily the sd-card, from the docs:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Example, just change your first line to be:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Need a directory?:
File dir = new File(Environment.getExternalStorageDirectory(), "yourdir");
dir.mkDirs();
File file = new File(dir, fileName);

Try this, Create file folder like this
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Foldername";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}

Related

Directory is generating instead of excel file

I am using Apache POI on android to export an excel file for my offline database. While creating a file instead of creating a .xls file its generates directories
//filename = "collectionreport.xls"
String path = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+File.separator+fileName;
File file = new File(path);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);
Log.e(TAG, "Writing file" + file);
isSuccess = true;
} catch (IOException e) {
Log.e(TAG, "Error writing Exception: ", e);
isSuccess = false;
} catch (Exception e) {
Log.e(TAG, "Failed to save file due to Exception: ", e);
isSuccess = false;
}
error:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/aa.bb.com.modules.tabbank/files/Download/CollectionReport163548565.xls (Is a directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:287)
at java.io.FileOutputStream.<init>(FileOutputStream.java:223)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)```
EDIT: It automatically worked after restarting my computer running on linux and re installing the application

Image not overwriting on same name

I'm developing image editor app.. so each time the user have to save the image.
So first i inserted
String savedImageURL = MediaStore.Images.Media.insertImage(
getContentResolver(),
bitmap,
"Bird",
"Image of bird"
);
this code, but it creating new file instead of overwriting.
So i use another method
public String saveImage(String folderName, String imageName) {
String selectedOutputPath = "";
if (isSDCARDMounted()) {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
// Create a storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("PhotoEditorSDK", "Failed to create directory");
}
}
// Create a media file name
selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
File file = new File(selectedOutputPath);
try {
FileOutputStream out = new FileOutputStream(file,true);
if (parentView != null) {
parentView.setDrawingCacheEnabled(true);
parentView.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return selectedOutputPath;
}
But it also didn't work.
Does anyone know about overwrite a bitmap in the same name?
Pass false as 2nd argument, to set append to false, so that you will overwrite the existing file:
FileOutputStream out = new FileOutputStream(file,false);
Check out the constructor documentation:
here is your code:
public String saveImage(String folderName, String imageName) {
String selectedOutputPath = "";
if (isSDCARDMounted()) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
// Create a storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("PhotoEditorSDK", "Failed to create directory");
}
}
// Create a media file name
selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
File file = new File(selectedOutputPath);
if (file.exists())
{
try {
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file,false);
if (parentView != null) {
parentView.setDrawingCacheEnabled(true);
parentView.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return selectedOutputPath;
}
I also had this situation, but it turns out that this is not a problem with saving, but with displaying in ImageViev. I used Glide, and it turns out to be stored in the cache when outputting. And I did not change the name and path of the file. That is, I rewrote them. But Glide did not know this. He thought they were the same file. To fix this problem, I added the following
Glide.with(context)
.load(file)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(view)
If you also have this situation and these solutions helped you, I'm glad to this.

Android app creates file but can't find it

I'm having an issue that is preventing me from releasing my app, so maybe you can help. I have this code to create and write to a file:
#Override
public void onClick (View view){
final String memoryString = memory.getText().toString();
File file = new File(getApplicationContext().getFilesDir(), filename);
FileOutputStream fos = new FileOutputStream(file);
if (location != null) {
String s = location.toString() + " " + memoryString;
Log.d(null, s);
if(fos != null) {
Log.d(null, "fos not null");
fos.write(s.getBytes());
} else {
Log.d(null, "Output Stream is null");
}
fos.close();
Log.d(null, "file created!");
}
} catch (IOException e) {
e.printStackTrace();
}
my log is saying that it's creating the file. but when I go to access and read from said file, I get the error here that it doesn't exist:
try {
File memoryFile = new File(filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
} else {
Log.d(null, "no file found");
}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
Please help if you are able, I am very much stuck
Maybe this ?
try {
File memoryFile = new File(getApplicationContext().getFilesDir(), filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
}else{Log.d(null, "no file found");}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
How is it that you created a file with this statement
File file = new File(getApplicationContext().getFilesDir(), filename);
And then try to retrieve the file with this
File memoryFile = new File(filename);
Why can't you use the same statement. How is the second statement supposed to determine the directory containing the file?

My app can create a file, but cannot read it

I write a file in internal memory:
byte[] data = ... // (A buffer containing wav data)
String filename = context.getFilesDir().getAbsolutePath() + "/newout.wav";
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
Then I try to play it:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filename);
player.prepare();
player.setLooping(false);
player.start();
But the prepare() fails:
java.io.IOException: Prepare failed.: status=0x1
I checked the file and saw that it's permission is -rw-------. I changed it to -rw-r--r--, after that it was being played successfully.
So how come my app can write a file, but can't read it? And how can I make the FileOutputStream to set the permissions right?
To change programaticaly the file permissions to -rw-r--r-- you need to do smoething like this:
Process process = null;
DataOutputStream dataOutputStream = null;
try {
process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
dataOutputStream.writeBytes("chmod 644 FilePath\n");
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
process.destroy();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
If you open a file, the default mode is Context.MODE_PRIVATE, e.g. as in
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
(taken from the documentation). Modes MODE_WORLD_READABLE and MODE_WORLD_WRITABLE are deprecated and do not work on newer devices. So I'd say you should rather write on the external storage to make contents available to other apps.
Note: as per documentation:
External storage:
"It's world-readable, so files saved here may be read outside of your control."

Impossible to create file on external storage Android

I want to create a .txt file and store it on the external storage of the Android phone. I added the permission to my Android Manifest. When I run the code it doesn't give me any error but the file is never created. Not sure what I am doing wrong.
public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = null;
OutputStreamWriter out = null;
os = myContext.openFileOutput(data, Context.MODE_PRIVATE);
out = new OutputStreamWriter(os);
out.write(data);
os.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
you need an appropriate permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
}
I was able to create the file on the external storage by using the code below:
public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}

Categories