I want to create a directory on sd card keeping it as a separate activity in one of my application. I wrote the following code in the onCreate() of the application. It is not creating the directory though this code works fine if I try to implement it as an independent application.
Please suggest a solution for this problem.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
String dirName = "/sdcard/TEST";
File newFile = new File(dirName);
newFile.mkdirs();
Log.d("CaptureTest.java","Directory created");
if(newFile.exists()){
Log.d("capturetest.java","directory exists");
if(newFile.isDirectory()){
Log.d("capturetest.java","isDirectory = true");
}
else Log.d("capturetest.java","isDirectory = false");
} else
{
Log.d("capturetest.java","directory doesn't exist");
}
} catch(Exception e){
Log.d("capturetest.java","Exception creating folder " + e);
}
........................................
..........................................
}
The SD card might be mounted at /mnt/sdcard instead of /sdcard.
But the safest technique to get the external storage directory is like in the following code
File myDirectory = new File(Environment.getExternalStorageDirectory(), "my directory");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
There could be a number of things causing this:
Check that external storage is available and writeable before trying to write to it.
Don't use String dirName = "/sdcard/TEST"; use Environment.getExternalStorageDirectory() or Context.getExternalFilesDir() instead.
This page has some really useful tips for correctly accessing the SD card.
Related
I can see sdcard folder contents by using this
File f = new File("/storage/extSdCard");
if (f.exists()) {
File[] files = f.listFiles();
if (files != null) {
for (File filz : files) {
Toast.makeText(this, filz.getName() + "", Toast.LENGTH_SHORT).show();
}
}
}
But when i try to create directories
File dir = new File("/storage/extSdCard/Android/Mayor");
try {
if (!dir.exists()) {
if (dir.mkdirs()) {
Toast.makeText(this, "Folder Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Folder Not Created", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "WTF", Toast.LENGTH_LONG).show();
}
Its doesnt create at all. Any idea?
// create a File object for the parent directory
File myDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
myDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(myDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Note:
It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
UPDATE:
Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to use DocumentFile.createDirectory(displayName) to create a directory on a removable SD card. See https://stackoverflow.com/a/35175460/1048340
File mnt = new File("/storage");
if (!mnt.exists())
mnt = new File("/mnt");
File[] roots = mnt.listFiles();
For read external sdcard, you need to mount sdcard path first then after you can able to use external sdcard path.
i am trying to load a html file in webView from sd card its not working, Directory exists in SD card as well as file in it. Here is the code i have tried.
public void CheckReg()
{
File file = new File(getExternalCacheDir(), "Reginfo/input/register.html" );
if (file.exists())
{
index.loadUrl("file:///sdcard/Reginfo/input/register.html");
Toast.makeText(mContext, "File Exists", Toast.LENGTH_SHORT).show();
}
}
do this
File file = new File(Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
if (file.exists())
{
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
dont forget to
add permissions to menifest
should set like ,
public void CheckReg()
{
File file = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"Reginfo/input/register.html" );
if (file.exists())
{
index.loadUrl("file:///"+file);
Toast.makeText(mContext, "File Exists", Toast.LENGTH_SHORT).show();
}
}
You shouldn't hard code the directory of the sdcard like that. Its typically at /mnt/sdcard/ but this is never assured instead of this you can write it like this.
and before you load the file from sd-card you make ensure that sd-card is mounted.
You can use the following:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(TAG, "No SDCARD");
} else {
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
}
I created a file by file.createNewFile() command in "data/data/com.android.bonvoyage" folder to test file creation in the internal storage of my android tablet.
I found that the file should be visible when I have root account, but I want to find a way
to see the file created without root permission.
I don't care where the file is created, just want to see and test it on actual tablet.
Can I do that?
The process was successful by
File file = new File("data/data/com.android.bonvoyage/myfile.txt");
boolean tf = false;
if (!file.exists()) {
try {
tf = file.createNewFile();
} catch (IOException ioe) {
Toast.makeText(this, ioe.toString(), 5000).show();
//ioe.printStackTrace();
} finally {
Toast.makeText(this, "File Created? " + Boolean.toString(tf), Toast.LENGTH_SHORT).show();
}
}
With root explorer or any file explorer that supports root you could browse to: data/data/com.android.bonvoyage/myfile.txt and look whether its there or not?
Write the file to the sdcard and then you can see it with the file browser without root permissions.
Use the following code (taking from the android guide) to open a file in the pictures folder for example:
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
The full guide can be found here:
http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage
I develop an app which collects some data from internet. Then save it to a temporary folder. To build this app I need to create and access a folder ( just for the purpose of app, not for the user). How can I do it?
this code is to create folder:
File direct = new File(Environment.getExternalStorageDirectory() + "/New Folder");
if(!direct.exists())
{
(direct.mkdir()) //directory is created;
}
try it may help you
File mFile;
onCreate()
mFile= new File(Environment.getExternalStorageDirectory()+"/temp/";
mFile.mkdir();
onDestroy();
mFile.delete();
try out this...
private void makeFolder(){
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + getString(R.string.folder_name));
boolean mainfolderexist = root.exists();
if (!mainfolderexist) {
try {
if (Environment.getExternalStorageDirectory().canWrite()) {
root.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
All The best
You should really check this other SO answer: https://stackoverflow.com/a/6485850/65716
Aside from the fact that you have to completely manage your use of the space, etc, caching on external storage requires more permission for your app.
See http://developer.android.com/reference/android/content/Context.html#getCacheDir()
"Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage."
For app use only, I would recommend to use Context.getDir() for retrieving the directory if the files is used by our app only and don`t want to be visible to users by file browsers.
// No need to check if exist, created automatically.
File tempRoot = context.getDir("temp", Context.MODE_PRIVATE);
// do something
i have a problem with my code that is supposed to write some data string to my sdcard. i use a class to do this:
public class CVS {
private String path;
private String filename;
private File dir;
private File file;
private FileWriter fw;
public CVS() {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/traffic/";
filename = "data.cvs";
file = new File(path, filename);
createDir();
}
private void createDir() {
dir = new File(path);
if(!dir.exists()) {
if(file.mkdirs() == false) {
Log.d(Config.LOGTAG, "UHOH!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
else Log.d(Config.LOGTAG, "dir exists");
}
public void writeToFile(String data) {
try {
fw = new FileWriter(file);
fw.append(data); Log.d(Config.LOGTAG, "data saved to file...");
}
catch(Exception e) {
Log.d(Config.LOGTAG, "file: " + e.getMessage());
}
}
}
this results ALWAYS in an exeption being caught in writeToFile(), saying "permission denied". actually, i set permissions to WRITE_EXTERNAL_STORAGE in the manifest. so - what am i doing wrong!?
additional info: real device with sd card mounted. no emulator. android 2.2. if i create the dir myself, the problem wont go away :(
Either:
Your manifest is wrong, or
Your external storage is mounted on your development machine, or
Your manual concatenation of your directory is wrong
Your code is ok but still you can add a check for whether sdcard is inserted or not, if you run this code and sdcard is not inserted then it will throw an exception, good practice is that you should always catch the exeptions.
you can check sdcard by following code...
if (android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_MOUNTED))
{
//code or logic if sd card is inserted....
}
else
{
Log.e("Exception","SD Card not found!");
}
All of the answers are needed, but if it's a Samsung device, then you need to append "/external_sd/" to the path - because they decided they needed to dork with our minds and break the API:
"http://developer.samsung.com/forum/board/thread/view.do?boardName=GeneralB&messageId=162934&messageNumber=1381&startId=zzzzz~&searchType=TITLE&searchText=sdcard