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

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();
}

Related

how to create a folder in android External Storage Directory?

I cannot create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
System.out.println("Path : " +Path );
File FPath = new File(Path);
if (!FPath.exists()) {
if (!FPath.mkdir()) {
System.out.println("***Problem creating Image folder " +Path );
}
}
Do it like this :
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
If you wanna create another folder into that :
File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}
The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail. Also, mkdir and mkdirs returns true only if the directory was created. If the directory already exists they return false
getexternalstoragedirectory() is already deprecated. I got the solution it might be helpful for you. (it's a June 2021 solution)
Corresponding To incliding Api 30, Android 11 :
Now, use this commonDocumentDirPath for saving files.
Step: 1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step: 2
public static File commonDocumentDirPath(String FolderName){
File dir = null ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
}
return dir ;
}
The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:
Context.getExternalFilesDir().
Example:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
file.delete();
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
return file.exists();
}
I can create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String folder_main = "Images";
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
if (!outerFolder.exists()) {
inerDire.createNewFile();
}
outerFolder.mkdirs(); // This will create a Folder
inerDire.createNewFile(); // This will create File (For E.g .jpg
file)
we can Create Folder or Directory on External storage as :
String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
File f=new File(myfolder);
if(!f.exists())
if(!f.mkdir()){
Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}
and if we want to create Directory or folder on Internal Memory then we will do :
File folder = getFilesDir();
File f= new File(folder, "doc_download");
f.mkdir();
But make Sure you have given Write External Storage Permission.
And Remember that if you have no external drive then it choose by default to internal parent directory.
I'm Sure it will work .....enjoy code
If you are trying to create a folder inside your app directory in your storage.
Step 1 : Add Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2 : Add the following
private String createFolder(Context context, String folderName) {
//getting app directory
final File externalFileDir = context.getExternalFilesDir(null);
//creating new folder instance
File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);
if(!createdDir.exists()){
//making new directory if it doesn't exist already
createdDir.mkdir();
}
return finalDir.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt";
}
This is raw but should be enough to get you going
// create folder external located in Data/comexampl your app file
File folder = getExternalFilesDir("yourfolder");
//create folder Internal
File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");
if (!file.exists()) {
file.mkdirs();
Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();
}
Try adding
FPath.mkdirs();
(See http://developer.android.com/reference/java/io/File.html)
and then just save the file as needed to that path, Android OS will create all the directories needed.
You don't need to do the exists checks, just set that flag and save.
(Also see : How to create directory automatically on SD card
I found some another thing too :
I had the same problem recently, and i tryed abow solutions and they did not work...
i did this to solve my problem :
I added this permission to my project manifests file :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
(plus READ and WRITE permissions) and my app just worked correctly.
try {
String filename = "SampleFile.txt";
String filepath = "MyFileStorage";
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}

How to rename a file?

A quick question, how do i rename a file?
File to = new File(f.getAbsolutePath(), etRenameStr.getText().toString() );
f.renameTo(to);
expl();
tried like that, but doesn't seem to work.
Thanks!
File dir = Environment.getExternalStorageDirectory();
if(dir.exist()){
File from = new File(dir,"from.mp4");
File to = new File(dir,"to.mp4");
if(from.exist())
from.renameTo(to);
}
http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29
I think getAbsolutePath() returns the full path including file name, that might be a problem here. Try getParent() instead and see if it works.
File rootDir = Environment.getExternalStorageDirectory();
File file = new File(rootDir + "/Files/"+fileName);
File file2 = new File("newname");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
System.out.println("File was not successfully renamed");
}
This worked for me. please check once!!

Get filenames from a directory in Android

I want to populate a spinner with the filenames of files found on the SD card with specific extensions. I can get it thus far to populate the spinner with the correct files, but the path is shown as well.
Can anyone tell me how to only get the filename of a specific file in a directory on the SD card?
File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, "path");
for (File f : yourDir.listFiles()) {
if (f.isFile())
String name = f.getName();
// Do your stuff
}
Have a look at Environment page for more info.
Try below code
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard, "yourpath");
for (File f : dir.listFiles()) {
if (f.isFile())
String name = f.getName();
// do whatever you want with filename
}
File filePath= new File(File Address);
File[] fileList = filePath.listFiles();
String name = fileList [0].getName().toString();
could you process the string in reverse order(right to left), finding the first slash, then cutting the string at that point and taking the rightmost part of the string as the filename ?
use method getName() of file object:
file.getName();
Above answers are giving null pointer exception in my case. Following code worked for me:
File yourDir = new File(Environment.getExternalStorageDirectory().getPath() + "/WhatsApp/Databases");
for (File f : yourDir.listFiles()) {
if (f.isFile())
name = f.getName();
// Do your stuff
}

Check if file exists on SD card on Android

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}

Delete file from internal storage

I'm trying to delete images stored in internal storage. I've come up with this so far:
File dir = getFilesDir();
File file = new File(dir, id+".jpg");
boolean deleted = file.delete();
And this is from another question, which was answered with:
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
My example always returns false. I can see the file fx 2930.jpg in DDMS in eclipse.
The getFilesDir() somehow didn't work.
Using a method, which returns the entire path and filename gave the desired result. Here is the code:
File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();
Have you tried Context.deleteFile() ?
Java
File file = new File(photoPath);
file.delete();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
new String[]{file.getName()},null);
Kotlin
val file = File(photoPath)
file.delete()
MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
arrayOf(file.getName()), null)
String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete();
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);
The code File dir = getFilesDir(); doesn't work because this is a request for a File object.
You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.
You can also use: file.getCanonicalFile().delete();
File file = new File(getFilePath(imageUri.getValue()));
boolean b = file.delete();
is not working in my case.
boolean b = file.delete(); // returns false
boolean b = file.getAbsolutePath.delete(); // returns false
always returns false.
The issue has been resolved by using the code below:
ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);
Have you tried getFilesDir().getAbsolutePath()?
Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.
> 2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created
2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it
solution1:
Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri
here I initialize Content resolver
and delete it with a passed parameter of that URI
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
solution2(my first solution-from head in this time I do know that ): content resolver exists...
String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);
File file = new File (path);
if (file != null) {
file.delete ();
}

Categories

Resources