public void reNameFileName(String filePath, String newFilename) {
String path = filePath;
String filename = path.substring( path.lastIndexOf( "/" ) + 1 );
File oldfile = new File(filename);
File newfile = new File(newFilename,".mp4");
/*oldfile.renameTo(newfile);*/
if (oldfile.renameTo(newfile)) {
Toast.makeText( VideoPlayActvity.this, "Rename succesful", Toast.LENGTH_LONG ).show();
} else {
Toast.makeText( VideoPlayActvity.this, "Rename failed", Toast.LENGTH_LONG ).show();
}
}
this is my code for rename file i am able to get old file name and try to replace it by new file name then each time it goes fail condition please suggest me where am doing mistake.
Have you given permission to the app in manifest file to write to external sd card? If not, like this.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, you can get the file storage directory with the following.
File sdcard = Environment.getExternalStorageDirectory();
Then, to implement the whole thing
File sdcard = Environment.getExternalStorageDirectory();
File first = new File(sdcard,"first.txt");
File rename = new File(sdcard,"rename.txt");
first.renameTo(rename);
Because the file path should never be hardcoded into the program, but the above function should be used
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 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 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);
}
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 have a section of code that is supposed to check if an mp3 file is stored in the SD card on the MediaStore.Audio.Media content provider
the problem is that no matter the situation. Either if the file with the pathname stored in variable "audioFilename" exists on the SD card or not. it always returns "this file does not exist" as the result. Despite the fact that the variable audioFilename has the String path name stored in it "/mnt/sdCard/Music/Jungle.mp3", and this MP3 file is actually on the SD card. Easy to prove with a Toast message and a check of the SD card contents.
I probably have an error in the use of File or Environment classes. Can anyone see a problem in the code shown here?
// toast message to prove that the audioFilename is not null,
// message displayed is the string, "File name: /mnt/sdCard/Music/Jungle.mp3"
Toast.makeText(Editor.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();
// the code below always returns "this file does not exist"
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
if(myFile.exists()){
Toast.makeText(Editor.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
Toast.LENGTH_LONG).show();
} else if(!myFile.exists()){
Toast.makeText(Editor.this, "<<<< this file does not exist >>>> ",
Toast.LENGTH_LONG).show();
}
Toast.makeText(Editor.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();
Are you sure have import java.io.File?
Try with :
String pathsd = Environment.getExternalStorageDirectory()+"/";
// so var pathsd will return "/mnt/sdcard/"
// then you must sure var audioFilename is Music/Jungle.mp3
File myFile = new File(pathsd + audioFilename);
Or are you sure with your path? if you not sure you can try give direct string path.
File myFile = new File("/mnt/sdCard/Music/Jungle.mp3");
Try to change this line
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
with
File myFile = new File(audioFilename);
I have run test with the same code and it is working well.
Here is the code I test with :
String audioFilename = "/sdcard/NewFolder/test1.jpg";
Toast.makeText(SimpleTest.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();
// the code below always returns "this file does not exist"
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(audioFilename);
if(myFile.exists()){
Toast.makeText(SimpleTest.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
Toast.LENGTH_LONG).show();
} else if(!myFile.exists()){
Toast.makeText(SimpleTest.this, "<<<< this file does not exist >>>> ",
Toast.LENGTH_LONG).show();
}
Toast.makeText(SimpleTest.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();
Hope it helps you.
Thanks.
You need to add permission in AndroidManifeast file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Edit :
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore+ "/Music/Jungle.mp3"); <---- try this
I'm just going to hazard a guess and assume that you are using a physical device to test your application. If this is true, your external storage may not be mounted (since you're using USB storage with the computer) so the file really doesn't exist according to the system. Try testing your code without the USB cord plugged in.
EDIT:
Remove the quotes around "audioFilename".
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
to
File myFile = new File(extStore.getAbsolutePath() + audioFilename);