Deleting a file with similar names in Java - java

I have like 2 files with almost same name like "myfile_1234.mp4" and "myfile_5678.mp4" in the same directory. One File, say, "myfile_1234.mp4" size is ZERO bytes where as the other file say "myfile_5678.mp4" has some size NOT EQUAL to ZERO (say 32kb). Now I want to delete the 1st File from the Directory but not the other File.
Can we have something like a loop temp pointer to the Files in the Directory and we would then check for Size of file and delete it when its size is ZERO.
Can anyone help me here...?

This is a relatively straightforward exercise. Here are the things that you need to know to do understand what to do:
A directory is represented by a File object. Create a File object for the directory that you want to list
The listFiles() call produces an array of all files in the directory
The length() method returns the size of the file
The delete() method deletes the file
Your code will look like this:
// Reference the directory in which the files reside
File dir = new File("c:/my/test/directory");
// Go through the files in the directory in a loop
for ( File file : dir.listFiles()) {
// Make sure that an entry is a file (it could be a directory)
// and that its size is zero
if (file.isFile() && file.length() == 0) {
// If both conditions are true, delete the empty file
file.delete();
}
}
You can make additional conditions to check if a file has a particular name, extension, etc.

You can have a file (handle) created like
File myFileOne = new File(path);
File myFileTwo = new File(anotherPath);
Having such handles it is quite easy to check files size or names and delete the files as well. For more info on Java File see: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#File

Related

Java getting absolute path from directory count list

Expected:
find the number files in the folder, and collect the absolute path for each file in the directory.
File certificatePath = new File("resources/NPL");
String absolutePath = certificatePath.getAbsolutePath();
File directory = new File(absolutePath);
int fileCount=directory.list().length;
From the above code getting the no of files in folder (resources/NPL), now i'm struggle to get the absolute path for the files.
You should use listFiles instead fo list() (provided you have the security rights to do so), otherwise you are stuck with the file names.
Well first of all what does it mean to collect it? If you need the file names it is already there for you in an array of String[] which you get from directory.list() method. If you want the full names you can use listFiles() method which returns a File[] and each file has getAbsolutePath() method. Something like:
for (File file : directory.listFiles()) {
System.out.println(file.getAbsolutePath());
}

list of file names sort to a specific order

My java code lists all code files under a directory of file system, and load each file one by one:
File[] files = mDir.listFiles();
for(File f: files) {
System.out.println(f.getPath());
//load code file
System.load(f);
}
The above code logically looks good, but is not suitable for my case.
My case is that I can NOT load them in a loop one by one, because there are dependencies among those code files. I need to load the files in a specific order according to dependencies.
Say, I already know there are following files under the directory mDir which should be load in the following order:
["dFile", "xFile", "aFile", "hFile"]
and I already got the directory instance mDir .
How can I load files with above order efficiently in java?
If you already know which files you are interested in then just load them in the proper order.
If you have to see which files are available first and then load them in the specific order, then use one loop to get the names of the existing files, then process the list by picking the correct files in the correct order.
I'd suggest just setting the working directory correctly (see Changing the current working directory in Java?) and then doing
for(String fname : fileArray) {
System.load(new File(fname));
}
(where fileArray is the list of file names) or
for(String fname : fileArray) {
System.load(new File(mDir.getPath() + fname));
}
if you're intent on loading from a specific directory.
Other than that, you'd need to divine the dependencies from each file in order, or read the list of files to load from some other source (an array, another file, whatever).

java - File length after rename

a simple question, I have the following java code:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
System.out.println(file.length());
If I run it, I see that the file has changed of name correctly, but strangely file.length() returns 0 (And the file is not empty)
Any idea?
Thank you
File is immutable. It will always point to the filepath you created it with.
So when you rename your file, the file to which your File object points doesn't exist anymore (it was renamed) and you get the file length of 0.
See also the javadoc.
Try this:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
File file2 = new File("mySecondFile.xls");
System.out.println(file2.length());

get all absolute paths of files under a given folder

I need to hold in memory all absolute paths of file names under a given directory.
myDirectory.list() - retrieves String[] of file names only (without their absolute paths).
Don't want to use File Object since it consumes more memory.
Last thing - I can use apache collections etc. (but didn't find anything useful for that).
String directory = <your_directory>;
File[] files = new File(directory).listFiles();
for(File file : files){
if(file.isFile()){
System.out.println(file.getAbsolutePath());
}
}
This works, and I gotta say I'm confused when you say you don't wanna use File objects, but whatever works, I guess.
Doesn't myDirectory holds the directory of all those files?
If so, just combine the path in myDirectory with each of the cells in the array myDirectory.list() returns.

Find Path During Runtime To Delete File

The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.
The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.

Categories