using external storage? - android

I want to use the sdcard as a storage support of my application's data, the problem I encountered the path varies depending on the manufacturer, I do not have the same configuration for all tablets. I used the code below.
File root = Environment.getExternalStorageDirectory();
String Path = root.getAbsolutePath().toString();
File mFile = new File(Path+ "/fileName");
if(mFile.exists()){
mFile.delete();
}
With some tablets the job is done and the file is deleted with other no. So can you tell me how to get the external storage for all tablets.

File has a constructor that takes two parameters. A file and a String.
File root = Environment.getExternalStorageDirectory();
File mFile = new File(root, "fileName");
if(mFile.exists()){
mFile.delete();
}

Related

File creation in SD card not working

I am trying to create a file and store it in SD Card to be used as an input for some processing for an apps.
After searching for a while, I got this code which can create a file in SD card.But after running this,I couldn't see any file created in my SD card. Can anyone please help me what I am missing here.
BufferedWriter out = new BufferedWriter(new FileWriter(FileDescriptor.err));
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File perffile = new File(root, "samplefile.txt");
FileWriter perfwriter = new FileWriter(perffile, true);
out = new BufferedWriter(perfwriter);
}
} catch (IOException e) {
Log.e(TAG, "-Could not write file " + e.getMessage());
return;
}
If you want to add a file or folder or move application into your SD Card just do the following:
steps:
1) Open your Android application's source code file with a text or programming editor.
2) Browse to the location in the source code where you wish to call the function that writes a file to the device's external storage.
3) Insert this single line of code to check for the SD card:
File sdCard = Environment.getExternalStorageDirectory();
4) Insert these lines of code to set the directory and file name:
File dir = new File (sdcard.getAbsolutePath() + "/folder1/folder2");
dir.mkdirs();
File file = new File(dir, "example_file");
// The mkdirs funtion will create the directory folder for you, use it only you want to create a new one.
5) Replace "/folder1/folder2" in the above code with the actual path where you intend to save the file. This should be a location in which you normally save your application files. Also, change the "example_file" value to the actual file name you wish to use.
6) Insert the following line of code to output the file to the SD card:
FileOutputStream f = new FileOutputStream(file);
Finally step 7:
Save the file, then compile it and test the application using the Android emulator software or the device.
This will works!!! ;-)

Removing "app_" prefix when creating subdirectories in application's internal storage

Android provides many options for storing data persistently on the device. I have opted for internal storage, so please don't make suggestions for storing on an SD card. (I've seen too many questions about internal storage have answers for SD cards!!)
I would like to create subdirectories in my application's internal storage directory. I followed this SO answer, reproduced below.
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 to write into the file.
Unfortunately, that's creating subdirectories with "app_" prefixes. So, from the example, the subdirectory looks like "app_mydir" (not ideal).
The answer to this SO question suggests that you can get rid of the "app_" prefix this way:
m_applicationDir = new File(this.getFilesDir() + "");
m_picturesDir = new File(m_applicationDir + "/mydir");
But I want to write a zip to something like /data/data/com.mypackages/files/mydir/the.zip.
So, in the end, my code looks like this:
File appDir = new File(getApplicationContext().getFilesDir() + "");
File subDir = new File(appDir + "/subDir");
File outFile = new File(subDir, "/creative.zip");
But, this is creating another error: "File does not exist" when I try this:
FileOutputStream fileStream = new FileOutputStream(outFile);
How can I (1) create a subdirectory without the "app_" prefix and (2) write a zip into it?
Also, if my first demand isn't reasonable, tell me why in the comments! I'm sure "app_" prefix has some meaning that escapes me atm.
Did you create the directories?
File appDir = getApplicationContext().getFilesDir();
File subDir = new File(appDir, "subDir");
if( !subDir.exists() )
subDir.mkdir();
File outFile = new File(subDir, "creative.zip");
Note that you shouldn't use / anywhere in your app, just in case it changes. If you do want to create your own paths, use File.separator.

What's the root of my android app?

I'm trying to develop a simple android app. I want to know if an image exist in one of my apps' folder, but I don't know what's the root of my app. I tried...
File nomeFile = new File("res/drawable-hdpi/imagename.jpg")
File nomeFile = new File("myappanem/res/drawable-hdpi/imagename.jpg")
...but it doesn't work.
Try This :
File YourFile = new File(Environment.getExternalStorageDirectory(), "/Android/data/....yourfile.txt");
No you cant access drawable or manifest after packaging. because there will be no "drawable" folder or manifest file at all. All your drawables packed in APK file after installation. You cant reach them.
But you can access any folder of your phone in your app like that.
Firstly make directory.
File directory = new File(Environment.getExternalStorageDirectory()+File.separator
+"Your folder");
directory.mkdirs();
Access your folder like that.
String fileUrl = "/Your folder/a.png";
String file = android.os.Environment.getExternalStorageDirectory().getPath() +
fileUrl;
File f = new File(file);
whether your taking about internal memory of your application cache directory
//use this for internal memory
String path =Environment.getDataDirectory().getAbsolutePath();
File myImage=new File(path,"your file name.extension");
//use this for cache directory
String path=getApplicationContext().getDir("" , Context.MODE_PRIVATE);
File myImage=new File(path,"your file name.extension")

save image to sdcard android Directory problem

Im trying to save data to sdCard first i tried to saave it privately within app directory on externalStorage using getExternalFilesDir but gives me nullPointerException so i tried the other way given below it worked but when i want to store files into a custom directory that i want to named myself it give me error:
FileOutputStream os;
dirName = "/mydirectory/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + dirName);
dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
File file = new File(dir, dirName+fileName);
os = new FileOutputStream(file);
}else{
os = context.openFileOutput(fileName, MODE_PRIVATE);
}
resizedBitmap.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
}
ErrorLog:
java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/myfile2.png (No such file or directory)
Your directory "/mnt/sdcard/mvc/mvc" may not exist. What about changing your path to store the image in the Environment.getExternalStorageDirectory() path and then working from there?
Also, as Robert pointed out, make sure you have write permission to external storage in your manifest.
Edit - to create directories:
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();
Then you can save a file to root + "/mvc/mvc/foo.png".
Have you requested permission to write onto SD card? Add the following string to you app manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should check if you have added the required permission android.permission-group.STORAGE to your app. Without that permission you won't be able to access anything on the SD-Card.
BTW: On the Android system I know the SD-card is mounted on /sdcard not /mnt/sdcard
I found this book to be very helpful: "Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets". I noticed a part that allows saving images and stuff to the SD card.

How to create a file on Android Internal Storage?

I want to save a file on internal storage into a specific folder. My code is:
File mediaDir = new File("media");
if (!mediaDir.exists()){
mediaDir.createNewFile();
mediaDir.mkdir();
}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();
getLocalPath returns /data/data/myPackage/files/media/qmhUZU.jpg but when I want to create the media folder I'm getting the exception "java.io.IOException: Read-only file system". Any ideas how to write my files on internal phone storage in in folder media? Thanks.
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
You should create the media dir appended to what getLocalPath() returns.
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/ somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");

Categories

Resources