I have been trying to fix an issue since yesterday but no luck yet. I made a very simple android application to create directory and the application was working fine. The main source code is mentioned here.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//View vi = null;
File extDir= Environment.getExternalStorageDirectory();
File sddir = new File(extDir+"/test10");
if (sddir.mkdirs()) {
Toast toast = Toast.makeText(this,
"Directory successfully created!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else{
Log.e(TAG, "Create dir in sdcard failed");
Toast toast = Toast.makeText(this,
"Directory creation failed!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
..... followed by remaining code
However, yesterday, when I integrated this code to my own application (a simple videolist that plays videos from the sd-card), the directory function, for whatever reasons, resulted in directory creation failed... I debugged the application but couldn't find exception errors or other errors in it. I don't know what could be wrong.. I am just wondering if there is any method to get the error statement behind directory creation failed. I mean if mkdirs failed, it could generate a small print statement about why it got failed??
any suggestions??
Please try with below function.
File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),"test10");
if (!cacheDir.exists())
cacheDir.mkdirs();
and declare <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in manifest file.
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Related
I want to write text to file in Android. I tried writing to sdcard and public part of internal storage. I always got FileNotFound exception. I tried to get path by Environment.getExternalStorageDirectory().getAbsolutePath() and by Environment.getExternalStoragePublicDirectory(Enviroment.DIRECTORY_DCIM).getAbsolutePath()(it does not metter the file is not a picture, I suppose) and both returned: "storage/emulated/0" and "storage/emulated/0/DCMI" respectively. I have also tried direct path "/sdcard/MyFile/output.txt" and "mnt/sdcard/MyFile/output.txt". I have checked on most stackoverflow.com answears in such topic but I got only code similar to mine. (like from here)
Example of my code (I tried more variations):
try {
File dir = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyFile");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(("some text").getBytes());
stream.close();
toast = Toast.makeText(context, "Saving file successful.", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
toast = Toast.makeText(context, Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT);
//toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
toast.show();
}
You have to set the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission in your AndroidManifest.xml file.
If you run your app on Android 6.0 or higher you have to request this permission at runtime.
Request App Permissions
I am sorry to all you guys to waste your time. The problem was in permission setting. Here is the answear.
I try a lot to create a folder in SD card in android 4.4.2 version.
i try the following code
String dirName="Test";
File file = new File(Environment.getExternalStorageDirectory(), dirName);
boolean status = file.mkdir();
if (status)
Toast.makeText(MainActivity.this,
"Directory created successfully", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(MainActivity.this, "Directory create failed",
Toast.LENGTH_SHORT).show();
but it creates a folder in internal storage.
and I try another code is
String path=System.getenv("SECONDARY_STORAGE");
File file=new File(path +"/Test123");
file.mkdir();
it creates a folder in External SDCARD in android 4.1 but not in android 4.4.2
So how can i create a folder in External sdcard in android 4.4.2??
If anyone know please help me..
Thanks in advance
The documentation states that
Applications should not directly use this top-level directory, in
order to avoid polluting the user's root namespace. Any files that are
private to the application should be placed in a directory returned by
Context.getExternalFilesDir, which the system will take care of
deleting if the application is uninstalled.
where with top-level directory they mean the return value of Enviroment.getExternalStorageDirectory()
Using getExternalFilesDir you will have
File file = new File (getExternalFilesDir(null), dirName);
if (!file.exists()) {
boolean status = file.mkdir();
if (status) {
Toast.makeText(MainActivity.this, "Directory created successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Directory create failed", Toast.LENGTH_SHORT).show();
}
}
also you should be aware of the fact that mkdir() returns false if the directory already exists
This should be self-explanatory.
String folderName = "NewFolder";
File file = new File(Environment.getExternalStorageDirectory(),
folderName);
if (!file.exists()) {
file.mkdirs();
}
Make sure you have added WRITE_EXTERNAL_STORAGE permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Credits to Dhaval
I am trying to create a text file in android internal storage but I am unable to do that. Can someone please tell me what am I doing wrong?
String append = "some data";
try {
FileOutputStream fileout=openFileOutput("fortify_profile.txt", Context.MODE_PRIVATE);
fileout.write(append.getBytes());
fileout.close();
Toast.makeText(getApplicationContext(), "Profile Created", Toast.LENGTH_LONG);
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not create Profile", Toast.LENGTH_LONG).show();
}
Every where I looked same method has been given to create a file on android internal storage but
mine is not working. Please help
Your code is correct and I hope that is creating file also. But you are not checking it in proper location. Go to data>data>your_package_name>files>fortify_profile.txt and that file should be there.
I'm trying to create a directory, and i'm checking whether it is created successfully or not but displaying a text on the screen, but nothing to be displayed.
Java code:
public void createDirectory() {
try {
String strDirectory = "test";
boolean success = ( new File(strDirectory)).mkdir();
if (success) {
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created", Toast.LENGTH_SHORT);
} else {
Toast.makeText(getApplicationContext(), "error occured", Toast.LENGTH_SHORT);
}
} catch (Exception e) {
Log.e("Error", "Error creating directory");
}
}
put .show() end of Both Toast....
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created",
Toast.LENGTH_SHORT).show();
Did you add uses-permission write external storage to your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I actually don't know where it's trying to create the directory since you are not qualifying the entire path. what are you trying to do?
If you are trying to create it on the SD card, do this,
File f = new File(Environment.getExternalStorageDirectory(), "myfile.txt");
http://developer.android.com/reference/android/os/Environment.html
Note that this file will be readable by all apps.
If you are trying to create a file that's private to the app, do this,
OutputStream os = context.openFileOutput("myfile.txt");
http://developer.android.com/reference/android/content/Context.html
Note that this method is reserved for small files as it uses the internal storage which is limited on many devices.
Finally, always print the stack trace,
Log.e("mytag", "some message", e);
9 times out of ten, this will point you directly to the problem.
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.