Cannot create a file? - android

I have a problem with creating files in Android. I have followed this tutorial, and wrote this method:
public File getStorageDir(String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File file = new File(path, name);
System.out.println(path);
if (!file.mkdirs()) {
System.out.println("Directory not created");
}
return file;
}
Path variable prints /storage/emulated/0/Documents, however if goes off and no such directory is created. I have added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
permissions to manifest file. I have tried using file.getParentFile().mkdirs() but got same result. What am I doing wrong?

You use below code to create folder.
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "folderName");
if (!folder.exists()) {
success = folder.mkdirs();
}

So turns out it was being created the whole time, just not visible in file explorer. I have fixed it with answer from this post. Final code looks like this:
public File getStorageDir(Context context, String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath();
File file = new File(path, name);
file.getParentFile().mkdirs();
MediaScannerConnection.scanFile(context, new String[] {path}, null, null);
return file;
}
Thanks everyone for answers, hope this helps someone who faces same problem.

Related

How to create a .txt file in a specific directory in Android?

I am trying to develop a program which creates a file in a specific directory (.txt file) and stores some data in it (Strings for example). I also want that the file can be accessed by the user (If I go to file explorer I can view the file I've created and maybe edit it with another program or something).
I've tried many things, but I cant manage this to work.
Here is the code I am using atm:
public void createFile(View view) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sonda Drive Test";
File mypath = new File(filepath);
if(!mypath.exists()) {
mypath.mkdir();
}
//now the mkdir returns true isntead of false
File myfile = new File(mypath, fileName);
try{
if(!myfile.exists()){
txtDebug.setText("Não existe ficheiro!");
myfile.createNewFile();
}
else{
txtDebug.setText("Já existe ficheiro!");
}
}catch (Exception e){
txtDebug.setText("Erro!");
}
}
I've also added the permissions bellow:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
The problem is that when I do
myfile.createNewFile();
The application stops and closes.. But if I comment that line, it also won't create any file...
What am I doing wrong?
EDIT: I Manage to make this work for API 22. How can i do it for API 25?
you are putting the mypath as the path but you define the mypath as file

How to create folder in external storage?

This is what I tried.
private void createFolderInExternalStorage() {
String storagePath = System.getenv("SECONDARY_STORAGE");
Log.e("storagePath->",storagePath);
String path = "not available";
if (storagePath != null) {
Log.e("Path->", "" + storagePath);
File file = new File(storagePath.toString());
Log.e("readable->", "" + file.canRead());
Log.e("writable->", "" + file.canWrite());
Log.e("executable->", "" + file.canExecute());
dir = new File(storagePath + File.separator+etFolder.getText().toString());
if (!dir.exists()) {
dir.mkdirs();
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" created",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" already exists",Toast.LENGTH_SHORT).show();
}
path = dir.getPath();
} else {
Toast.makeText(this,"External Storage not available",Toast.LENGTH_SHORT).show();
}
tv.setText("External SDCARD path->" + path);
}
if Secondary storage is present then System.getenv("SECONDARY_STORAGE") return /storage/sdcard1 in my case but getting following:
03-21 12:02:26.827 14155-14155/com.think.teststorage E/readable->: false
03-21 12:02:26.827 14155-14155/com.think.teststorage E/writable->: false
03-21 12:02:26.828 14155-14155/com.think.teststorage E/executable->: false
Even in some devices getting the above status as true but folder creation fails.
I have added the permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Suggestions are welcome.
You can use this code to create a folder.
File dir = new File("path/of/your/folder");
try{
if(dir.mkdir()) {
System.out.println("Folder created");
} else {
System.out.println("Folder is not created");
}
}catch(Exception e){
e.printStackTrace();
}
Add this permission also :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For further reference : see this link
Let me know if this works for you! :)
Use the following lines:
//Define the path you want
String path = Environment.getExternalStoragePublicDirectory(Environment.YOUR_DIRECTORY) + File.separator + "YourFolderName";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
YOUR_DIRECTORY is the directory where you want to create the folder, for example: DIRECTORY_DOCUMENTS, DIRECTORY_DOWNLOADS, DIRECTORY_PICTURES etc.
In your manifest should to add permission for write:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it help!
It is very simple and straightforward in android
`
File mFolder = new File(Environment.getExternalStorageDirectory(), "Folder_Name");
if (!mFolder.exists()) {
mFolder.mkdirs();
mFolder.setExecutable(true);
mFolder.setReadable(true);
mFolder.setWritable(true);
}
`
Also include required permissions in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Just put these lines of code,
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
and add require permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Does not work on KitKat, external, physical sdcard ??
then use use
Environment.getExternalStorageDirectory().getPath();

Save a file in Android

I'm currently using this code to store a file in Android:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/invoices";
File file = new File(dir, "Invoice.pdf");
This works perfectly fine in Genymotion emulator because ? but when I deploy the app to an Android phone, it doesn't work.
Can anyone explain why this maybe, or hint me to the right direction please, thanks in advance.
Add Permission in manifest file <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And Try This to Save File/Image
You should post all you did because from your code nobody can understand what you are exactly doing. However, take a look at the following links:
1. http://codetheory.in/android-saving-files-on-internal-and-external-storage/.
At the link mentioned above it explains you how to save in both internal and external SDcard.
2. http://developer.android.com/training/basics/data-storage/files.html.
Second link is from Google and it is a small brief about what you should do.
In all the cases don't forget about the permissions.
EDIT:
Below I attached a piece of code that it can help you:
public static File getNewFile(String fileName) throws IOException {
File file = null;
if (name == null) {
name = "temp_folder";
}
if (getInternalFilesDir() == null || !getInternalFilesDir().isDirectory()) {
file = null;
} else {
file = new File(getInternalFilesDir() + File.separator + TEMP_FOLDER + File.separator + fileName);
if (file.getParentFile() != null && ! file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file exists()) {
file.delete();
}
file.createNewFile();
if (! file.exists()) {
throw new IOException("Unable to create file " + name);
}
}
return file;
}
getInternalFilesDir is exactly that:
Save files in internal directory
//in the manifest now:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
other stuff
</manifest>

File.mkdir() and mkdirs() are creating file instead of directory

I use the following code:
final File newFile = new File("/mnt/sdcard/test/");
newFile.mkdir(); // if I use mkdirs() result is the same
And it creates an empty file! Why?
You wouldn't use mkdirs() unless you wanted each of those folders in the structure to be created. Try not adding the extra slash on the end of your string and see if that works.
For example
final File newFile = new File("/mnt/sdcard/test");
newFile.mkdir();
When I need to ensure that all dirs for a file exist, but I have only filepath - i do
new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();
First of all you shouldn't use a file path with "/mnt/sdcard/test", this may cause some problems with some android phones. Use instead:
public final static String APP_PATH_SD_CARD = "/Test";
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD;
It creates an empty file since you added the dash.
Now that you have your path use the following code:
try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
}
catch(Exception e){
Log.w("creating file error", e.toString());
}
Try to use
String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
File file=new File(rootPath);
if(!file.exists()){
file.mkdirs();
}

How to create directory automatically on SD card

I'm trying to save my file to the following location
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/" it works.
Now I'm assuming that I'm not able to create directory automatically this way.
Can someone suggest how to create a directory and sub-directory using code?
If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, 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" />
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is what works for me.
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in your manifest and the code below
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Actually I used part of #fiXedd asnwer and it worked for me:
//Create Folder
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
folder.mkdirs();
//Save the path as a string value
String extStorageDirectory = folder.toString();
//Create New file and name it Image2.PNG
File file = new File(extStorageDirectory, "Image2.PNG");
Make sure that you are using mkdirs() not mkdir() to create the complete path
With API 8 and greater, the location of the SD card has changed. #fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).
You can read more in the SDK documentation.
Make sure external storage is present:
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
private boolean isExternalStoragePresent() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
.show();
}
return (mExternalStorageAvailable) && (mExternalStorageWriteable);
}
Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)
not allowed characters in file/folder names
" * / : < > ? \ |
U may find this code helpful in such a case.
The below code removes all ":" and replaces them with "-"
//actualFileName = "qwerty:asdfg:zxcvb" say...
String[] tempFileNames;
String tempFileName ="";
String delimiter = ":";
tempFileNames = actualFileName.split(delimiter);
tempFileName = tempFileNames[0];
for (int j = 1; j < tempFileNames.length; j++){
tempFileName = tempFileName+" - "+tempFileNames[j];
}
File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
}
}
//Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}
File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();
this will create a folder named dor in your sdcard.
then to fetch file for eg- filename.json which is manually inserted in dor folder. Like:
File file1 = new File(sdcard,"/dor/fitness.json");
.......
.....
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and don't forget to add code in manifest
This will make folder in sdcard with Folder name you provide.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
if (!file.exists()) {
file.mkdirs();
}
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
ivmage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`

Categories

Resources