How to delete file in SD card? [duplicate] - java

This question already has answers here:
How to delete a file from SD card
(14 answers)
Closed 9 years ago.
I use this code:
String path = "mnt/sdcard/ten-file.mp3";
File file = new File(path);
boolean result = file.delete();
But it doesn't delete the file. Any advice?

String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ten-file.mp3";
File soundFile = new File(fileName);
if (soundFile.exists())
{
boolean result = file.delete();
}
Manifest permission
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

You want to make sure that the file exists prior to actually deleting the file:
File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
if(file.exists()) {
boolean result = file.delete()
}
The issue I think with your original code is that you didn't actually test to make sure the file existed. You just created a file variable then told it delete it. I referred to the following question from an individual who had a similar problem to you:
Android how to check if file exist and else create one?

Related

Moving files is not working in java [duplicate]

This question already has answers here:
How do I move a file from one location to another in Java?
(11 answers)
Closed 6 years ago.
i'm trying in a loop to move files after they are loaded and processed...when I test moving file part individually it works but when I do it all at once it does not work.
Bellow works fine, but moves directories also but I want only the file to be moved.
public class moveFiles {
public static void main(String[] args) {
String getFilesFrom = "D:\\show\\from";
String destDir = "D:\\show\\to\\";
File srcFile = new File(getFilesFrom);
srcFile.renameTo(new File(destDir, srcFile.getName()));
}
}
The code that I have which is not working the moving part is bellow.
for (File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
fr = new FileReader(child);
cm.copyIn("COPY ct"+addExtraZero+month+" FROM STDIN WITH DELIMITER ',' csv", fr);
} else {
System.out.println("No File is elgible to be loaded");
break;
}
getNumberOfFilesProcessed++;
System.out.println("Loading now " + child.getName());
child.renameTo(new File(moveFilesTo, child.getName()));
}
System.out.println("Number of files Loaded is: " + getNumberOfFilesProcessed);
The above code is:
get files from source directory,
loaded it in database
print files name that it loads
get count of files loaded
which all above works but the last part which is to move files to other directory after loading is not working bellow is the section of files that suppose to move the file the loop.
child.renameTo(new File(moveFilesTo, child.getName()));
scratching my heads for two hours any help will be appreciated.
From description of File.renameTo() (emphasis mine):
The rename operation might not be able to move a file from one
filesystem to another, it might not be atomic, and it might not
succeed if a file with the destination abstract pathname already
exists. The return value should always be checked to make sure that
the rename operation was successful
Add:
if( !child.renameTo(new File(moveFilesTo, child.getName())) )
System.out.println("Could not move file");
Or try using move(Path, Path, CopyOption...) method, as this has more options (using File.toPath()).

Loading file from resource gives a wrong path [duplicate]

This question already has answers here:
How to get a path to a resource in a Java JAR file
(17 answers)
Closed 7 years ago.
I have a propeties file with a path to a file inside my jar
logo.cgp=images/cgp-logo.jpg
This file already exists:
I want to load this file within my project so I do this:
String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg"
File file = new File(getClass().getClassLoader().getResource(property).getFile());
But then when I do file.exists() I get false. When I check file.getAbsolutePath() it leads to C:\\images\\cgp-logo.jpg
What am I doing wrong?
Well a file inside a jar is simply not a regular file. It is a resource that can be loaded by a ClassLoader and read as a stream but not a file.
According to the Javadocs, getClass().getClassLoader().getResource(property) returns an URL and getFile() on an URL says :
Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the concatenation of the value of getQuery(), if any. If there is no query portion, this method and getPath() will return identical results.
So for a jar resource it is the same as getPath() that returns :
the path part of this URL, or an empty string if one does not exist
So here you get back /images/cgp-logo.jpg relative to the classpath that does not correspond to a real file on your file system. That also explains the return value of file.getAbsolutePath()
The correct way to get access to a resource is:
InputStream istream = getClass().getClassLoader().getResourceAsStream(property)
You can use the JarFile class like this:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}

Why won't my file rename itself?

I am working on an android app and I want to rename a file. The problem is that it is not renaming:
File f = adapter.getItem(i);
File file = new File(f.getAbsolutePath(), "helloworld");
if (f.renameTo(file)) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
}
Solution BIg Thanks to #S.D.(see comments)
File f = adapter.getItem(i);
File file = new File(f.getParent(), "helloworld");
if (f.renameTo(file)) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
}
I think the issue is that:
File f = adapter.getItem(i);
Gives use some File f, say where f cooresponds to say: user2351234/Desktop. Then, you do:
File file = new File(f.getAbsolutePath(), "helloworld");
Which says to make a File file, where file cooresponds to: user2351234/Desktop/helloworld. Next, you call:
f.renameTo(file)
which attempts to rename f, user2351234/Desktop to user2351234/Desktop/helloworld, which doesn't make sense since in order for user2351234/Desktop/helloworld to exist, user2351234/Desktop would have to exist, but by virtue of the operation it would no longer exist.
My hypothesis may not be the reason why, but from Why doesn't File.renameTo(…) create sub-directories of destination?, apparently renameTo will return false if the sub-directory does not exist.
If you want to just change the name of the file, do this:
File f = adapter.getItem(i);
String file = f.getAbsolutePath() + "helloworld";
f = new File(file);
EDIT:
My proposed solution should work, but if my hypothesis about why your way does not work is incorrect, you may want to see this answer from Reliable File.renameTo() alternative on Windows?
Question 1: Do you see an exception or does it return false?
Question 2: Did you give permission for the app to write to the SD card? (I'm assuming that's where this file lies).
The permission to add is"
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This posting: How to rename a file on sdcard with Android application? seems to answer a similar question.
use this code.
File sdcard = Environment.getExternalStorageDirectory()+ "/nameoffile.ext" ;
File from = new File(sdcard,"originalname.ext");
File to = new File(sdcard,"newname.ext");
from.renameTo(to);

Show issue while deleting directory [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Delete a folder on SD card
In my app i saved all my data using internal storage i.e file. So at the first instance by using the ContextWrapper cw = new ContextWrapper(getApplicationContext()); class i get the directory path as m_AllPageDirectoryPath = cw.getDir("AllPageFolder", Context.MODE_PRIVATE); Inside this directory path i saved some file File as Page01, page02, Page03 and so on.
Again inside Page01 i saved some file like image01, image02...using the same concept m_PageDirectoryPath = cw.getDir("Page01", Context.MODE_PRIVATE); Now on delete of m_AllPageDirectoryPath i want to delete all the file associate with it. I tried using this code but it doesn't work.
File file = new File(m_AllPageDirectoryPath.getPath());
file.delete();
Your code only works if your directory is empty.
If your directory includes Files and Sub Directories, then you have to delete all files recursively..
Try this code,
// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
(Actually you have to search on internet before asking like this questions)

Deleting random access file in java

I've created a random access file as follows:
RandomAccessFile aFile = null;
aFile = new RandomAccessFile(NetSimView.filename, "rwd");
I want to delete the file "afile". can anyone suggest me how to do it?
You can do that:
File f = new File(NetSimView.filename);
f.delete();
Edit, regarding your comment:
The parameter NetSimView.filename seems to be a File and not a String that contains the path to the file. So simply do:
NetSimView.filename.delete();

Categories