the following code is deleting files and DIRS in a specific folder.
How could I adjust it, so it will delete only the files in the folder but not the dirs inside
code:
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
thanks,
ray.
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
if( !listOfFiles[i].isDirectory() ){ // if not a directory...
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
}
Make sense? :)
Easy ...
if (!listOfFiles[i].isDirectory()) {
listOfFiles[i].delete();
}
FWIW - your current code will only delete empty subdirectories. According to the javadoc, deleting a directory that is non-empty will fail; i.e. return false.
You have to use File.isDirectory
if(!listOfFiles[i].isDirectory())
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
http://download.oracle.com/javase/6/docs/api/java/io/File.html#isDirectory()
if (!listOfFiles[i].isDirectory()) { listOfFiles[i].delete(); }
Related
There are a few questions on stack which ask exactly this and yet none of the answers seem to resolve the issue in any way. Please note I am using the processing environment to code, which uses java, but with a wrapper. All java code works natively though.
Code is running on android 10 huawei mate 20 emui 10.
Here is my code. Only the first for loop returns any values, returning "emulated", "sdcard0", and "self", however the subsequent folders return null with the same functions. Permissions have been set in the manifest and in the pde app.
import android.os.Environment;
import android.os.Build ;
import android.app.Activity;
import android.content.Context;
Permission rStorage,wStorage;
void setup(){
rStorage = new Permission(this,"READ_EXTERNAL_STORAGE");
rStorage = new Permission(this,"WRITE_EXTERNAL_STORAGE");
//String path = Environment.getExternalStorageDirectory("storage/").toString();
//println("Files", "Path: " + path);
File directory = new File("storage/");
File[] files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files",null);
directory = new File("storage/emulated");
files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files emulated",null);
directory = new File("storage/sdcard0");
files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files sdcard0",null);
directory = new File("storage/self/");
files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files self",null);
};
void draw(){
};
my permission class
public class Permission{
PApplet parent;
public boolean requestedPortraitImage = false;
public Permission(PApplet pParent,String permissionName) {
parent = pParent;
parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
println(permissionName);
};
public void onPermissionResult(boolean granted) {
if (!granted) {
PApplet.println("User did not grant camera permission. Camera is disabled.");
}
};
};
I need to identify the file numbers which are missing in a folder.
I have retrieved the files names by using the code below :
File folder = new File(FILE_PATH);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
But now after retrieving i need to find which are the file number which are missing from a file range of 1-1976 both included.
If you need just the filenames, you may use list() method. After you get all the filenames with this method, you can just check the presence of the specified filenames, like:
File parent = ...
String prefix = "xxx_", suffix = ".txt"; // for example
Set<String> files = new HashSet<>(Arrays.asList(parent.list()));
// or, as suggested by #JulienLopez:
String pattern = Pattern.quote(prefix) + "\\d+" + Pattern.quote(suffix);
Set<String> files = new HashSet<>(Arrays.asList(parent.list((dir, file) -> file.matches(pattern))));
for (int i = 1; i <= 1976; ++i) { // actually constant should be used
if (!files.contains(prefix + i + suffix)) {
System.out.format("File #%d doesn't exist%n", i);
}
}
But if you really need to check, that the file is not, for example, the directory, there's one more way to do it, by just creating the Files for every i and checking its existence:
for (int i = 1; i <= 1976; ++i) {
File file = new File(parent, prefix + i + suffix);
if (!file.isFile()) {
System.out.format("File #%d doesn't exist or is directory%n", i);
}
}
I'm not sure your structural of your file name , and what exactly on your mind with "both included". That is my idea,I hope it's a bit help for you.
String FILE_PREFIX= "your_file_prefix"; // Your file prefix. If your file is "logfile_on_20160121_0001" then the prefix is "logfile_on_20160121_"
int RANGE_MIN = 1;
int RANGE_MAX = 1976;
int fileList[] = new int[RANGE_MAX];
int directoryList[] = new int[RANGE_MAX];
// Quote your code with a bit modify from me
File folder = new File(FILE_PATH);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
// Added started
String tempSplitedName[] = listOfFiles[i].split(FILE_PREFIX);
if(tempSplitedName.length==2){
int seq = Integer.parseInt(tempSplitedName[2]);
if(seq>=RANGE_MIN && seq<=RANGE_MAX){
fileList[seq] = 1;
}
}
// Added ended
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
// Added started
String tempSplitedName[] = listOfFiles[i].split(FILE_PREFIX);
if(tempSplitedName.length==2){
int seq = Integer.parseInt(tempSplitedName[2]);
if(seq>=RANGE_MIN && seq<=RANGE_MAX){
directoryList[seq] = 1;
}
}
// Added ended
}
// Now you count missing files/directory, which is equal 0
for (int i=RANGE_MIN; i<=RANGE_MAX; i++){
if(fileList[i]==0) System.out.println("Missing file No." + i);
}
for (int i=RANGE_MIN; i<=RANGE_MAX; i++){
if(directoryList[i]==0) System.out.println("Missing directory No." + i);
}
I'm trying to rename files in a folder. But instead all of them get deleted
File thisFolder = new File("C:\\ . . . ");
File [] filesArray = thisFolder.listFiles();
int filesArrayLength = filesArray.length;
if (filesArray != null) {
for (int i = 0; i < filesArrayLength; i++) {
filesArray[i].renameTo(new File("test" + i + ".pdf"));
}
}
What am i doing wrong ? Why do all of the files get deleted instead of renamed
As #Pshemo pointed out you might be moving the file to the current directory. Try doing this instead. This will tell it to create the file under the given parent directory:
filesArray[i].renameTo(new File(thisFolder, "test" + i + ".pdf"));//thisFolder is your parent directory
String strFilePath= "C:/Users/";
public void renameFile(String strOldFileName, String strNewFileName) {
File oldName = new File(strFilePath + "/" + strOldFileName);
File newName = new File(strFilePath + "/" + strNewFileName);
if (oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
Code example for you to rename the List of files in a given directory as below,
Suppose C:\Test\FileToRename isthe folder, the files which are listed under that has been renamed to test1.pdf,test2.pdf... etc..
File folder = new File("\\Test\\FileToRename");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File("c:\\Test\\FileToRename\\"+listOfFiles[i].getName());
f.renameTo(new File("c:\\Test\\FileToRename\\"+"test"+i+".pdf"));
}
}
I got my program to delete files within a specified file, but then I decided for it to delete the entire directory! This is my code so far, it does nothing when pressing the button... (and the button does have an ActionListener on it).
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(a)) {
int ans = JOptionPane.showConfirmDialog(null, "You're about to premenently delete this account! Are you sure you want to continue?", "Caution!!", JOptionPane.YES_NO_OPTION);
if (ans == JOptionPane.YES_OPTION){
//delete
File directory = new File("FileIO Plug-Ins\\Accounts\\" + user);
deleteDirectory(directory);
}
run();
}
}
public boolean deleteDirectory(File directory) {
if(directory.exists()){
File[] files = directory.listFiles();
if(files != null){
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
System.out.println("deleting: " + files[i].getName());
files[i].delete();
}
}
}
}
return(directory.delete());
}
the for loop I made does indeed find all the files in the specified folder, and the line
System.out.println("deleting: " + files[i].getName());
does also print every file within the 'user' directory, but doesn't delete them. nor does it delete the folder itself.
Please help! any advise or code source would be great!
delete() returns boolean value which you are ignoring.
true - if and only if file or directory was successfully deleted
false - if could not be deleted for some reason
To get the reason, use Files#delete(Path) for deleting the directory, as it gives you exception if the file cannot be deleted due to some reason.
Quoting the JavaDoc for File#delete()
Note that the Files class defines the delete method to throw an
IOException when a file cannot be deleted. This is useful for error
reporting and to diagnose why a file cannot be deleted.
I ran your code in my machine,it's work well.Maybe you don't have permission to delete your target directory.You can test with my code to find out which file's delete operation is failed.
public static boolean deleteDirectory(File directory) {
if(directory.exists()){
File[] files = directory.listFiles();
if(files != null){
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
if(files[i].delete()) {
System.out.println("Successfully delete: " + files[i].getAbsolutePath());
} else {
System.out.println("Failed to delete: " + files[i].getAbsolutePath());
return false;
}
}
}
}
}
if(directory.delete()){
System.out.println("Successfully delete: " + directory.getAbsolutePath());
return true;
} else {
System.out.println("Failed to delete: " + directory.getAbsolutePath());
return false;
}
}
I wanted to see all the files I have in my external storage, I have this library that display the text to the user, but when I'm using it to show the sub files, it says something like :
(Ljava.File;# How do I get it to show the name of the actual files to the user? Also, how can I show the name for a specific folder to the user? say file #3?
File[] files = myDir.listFiles();
UIHelper.displayText(this, R.id.textView1, files.toString());
Checl if sdcard is mounted or not.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
///mounted
}
Get the path of sd card
File dir= new File(android.os.Environment.getExternalStorageDirectory());
Then call
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {// if its a directory need to get the files under that directory
walkdir(listFile[i]);
} else {// add path of files to your arraylist for later use
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
This is the code for printing list of files and folders from ExternalStorage
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
Don't forget to put below permission in you android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use a recursive method to scan all your SD card:
String sdCardState = Environment.getExternalStorageState();
if( !sdCardState.equals(Environment.MEDIA_MOUNTED ) ) {
//displayMessage("No SD Card.");
return;
} else {
File root = Environment.getExternalStorageDirectory();
lookForFilesAndDirectories(root);
}
// lookForFilesAndDirectories() method:
public void lookForFilesAndDirectories(File file) {
if( file.isDirectory() ) {
String[] filesAndDirectories = dir.list();
for( String fileOrDirectory : filesAndDirectories) {
File f = new File(dir.getAbsolutePath() + "/" + fileOrDirectory);
lookForFilesAndDirectories(f);
}
} else {
doSomethingWithFile(f);
}
}