I know how to delete a file, it's:
File file = new File(path);
file.delete();
Can I test that the file is currenlty in use without rooting my device?
For exmple I want to check if the file is open before i can delete it.
I want to be able to catch errors with a try catch sentence.
You can use a try/catch clause.
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
You can find more information here.
Related
I'm working on a POC where I need to create and later on delete a file in the /data/data dir of a rooted device. I have tried to create a file in the standard way but it throws an PERMISSION_DENNIED exception as expected.
I know this is possible because the Root Explorer app can do it.
How can I programatically create/ delete a file via root?
Thank in advance!
Based on #GabeSechan comment I was able to achieve this using this commands.
Create new file:
final String[] sCommand = {"su", "-c", "touch /data/..."};
try {
Runtime.getRuntime().exec(sCommand);
} catch (Exception e) {
Log.e(TAG, "Issue occurred while creating new file " + e.getMessage());
}
}
And delete file:
final String[] sCommand = {"su", "-c", "rm /data/..."};
try {
Runtime.getRuntime().exec(sCommand);
} catch (Exception e) {
Log.e(TAG, "Issue occurred while deleting " + e.getMessage());
}
On my code I use:
mp = new MediaPlayer();
String filePath = Environment.getExternalStorageDirectory().getPath() + "/mymusic/asong.mp3";
try {
mp.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
And on the emulator the song.mp3 is played normally. But when I test it on my real device, it gives an error (-38, 0). That means it can not find the path of the song. I connect the usb cable, go to my Computer, GT-I8260 and paste the folder "mymusic" (that contains asong.mp3) under "Card" folder (where an empty folder named "LOST.DIR" is also placed). But why doesn't it work? Thanks a lot
it's card but at least
Environment.getExternalStorageDirectory() + "/mymusic/asong.mp3";
is enough.
Make sure it exists because you may not have the folder created before.
File f = new File(Environment.getExternalStorageDirectory() + "/mymusic");
if (!f.exists()) { f.mkdirs(); }
also make sure that it's not mounted while writing, since it may happen that it is not accessable at all.
Also revalidate that you have setupted the manifests permission to read/write the external storage
This one has me stumped (Android 4.3)
I have the right permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
... I'm explicitly creating a path to /storage/sdcard0/path/to/data.csv and the FileOutputStream doesn't throw any exceptions.
I tried reading the path via Environment.getExternalStorageDirectory() but that has some "emulated" path.
In either case, I can't see the files on the filesystem ...
What's more confusing is that MEDIA_MOUNTED_READ_ONLYis mounted_ro ... but this isn't the case .
It looks like another app us using /mnt/extSdCard... I tried hard coding that in my app but that doesn't work either. Even the directory is missing. This is very confusing.
I'm calling mkdirs() on this of course and the FileOutputStream is created....
What am I doing wrong?
Try the following code, and see where it fails?
try {
File mPath = new File(android.os.Environment.getExternalStorageDirectory(),"path/to");
if (!mPath.exists()) {
if(!mPath.mkdirs()) {
Log.e(getClass().getName(), "Can't Create Folder: "+mPath.getName());
}
}
File mLogFile = new File(mPath, "data.csv");
FileWriter mFileWriter = null;
if(mPath.canWrite()) {
mFileWriter = new FileWriter(mLogFile, true);
mBufferedWriter = new BufferedWriter(mFileWriter);
}
else {
Log.e(getClass().getName(), "Can't write under Folder: "+mPath.getName());
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I'm making a video downloader app and I've got no problems saving and deleting files downloaded by the app to external storage but any file transfered from my computer cannot be deleted by the app.
This is a real problem as it's one of the key features I want. Here's the code I'm using:
public boolean deleteDataFromStorage(Data toDelete) {
//The file object soon to be deleted
File f = null;
Log.e(TAG, "Deleting " + toDelete.fileName);
// Delete file from storage
try {
// Get file to delete
f = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + DIRECTORY + toDelete.fileName);
} catch (IOException e) {
Log.e(TAG, e.toString());
// Print to stack trace
e.printStackTrace();
}
// Delete file
if(f.delete()) {
return true;
} else {
Log.e(TAG, "Failed to delete " + toDelete.fileName);
return false;
}
}
As the f.delete() function doesn't throw any exceptions I have no idea what the problem is. The only thing I can think of is that the app doesn't have the permission to delete a file created in windows and yet I have downloaded apps from the app store that have no problem deleting transfered files.
Any help would be greatly appreciated.
As per your comment, since f.isFile() and f.exists() returns false, your f is not a file, in other words, you're getting the path wrong.
Print to the logs f.getAbsolutePath(), check what it is, and then it should be easy to fix.
As described in android documentation, to create a new file which will be situated in the application's directory there is the method in Context class: openFileOutput().
But where will be the file situated if I use simple createNewFile() method from File class.?
CreateNewFile() is used like this:
File file = new File("data/data/your package name/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
So you will tell the file where it should be created. Remember that you can only create new files on your package. That is "data/data/your package name/".
Somehow createNewFile() was not able to create the complete file path here on my devices.
try {
if (!futurePhotoFile.exists()) {
new File(futurePhotoFile.getParent()).mkdirs();
futurePhotoFile.createNewFile();
}
} catch (IOException e) {
Log.e("", "Could not create file.", e);
Crouton.showText(TaskDetailsActivity.this,
R.string.msgErrorNoSdCardAvailable, Style.ALERT);
return;
}
it will be stored in the current directory to which your classPath is pointing to
Depends on the path you pass to the File constructor. If the parent directory exists, and if you have the permission to write to it, of course.
Documentation of createNewFile() method says:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
Therefore we don't need to check existence of a file manually:
val dir = context.filesDir.absolutePath + "/someFolder/"
val logFile = File(dir + "log.txt")
try {
File(dir).mkdirs() // make sure to call mkdirs() when creating new directory
logFile.createNewFile()
} catch (e: Exception) {
e.printStackTrace()
}