tags:

views:

80

answers:

4

I'm working on a small application in Java that takes a directory structure and renames the files according to a certain format, after parsing the original name.

What is the best Java class / methodology to use in order to facilitate these file operations?

Edit: the question is only regarding the file operations part, I got the "getting the formatted name" down :)

Edit 2: Also, how do I list files recursively?

A: 

There's the class File, that does all you need:

tangens
+3  A: 

Use java.io.File


Listing all files in a directory

http://www.javaprogrammingforums.com/java-code-snippets-tutorials/3-how-list-all-files-directory.html

File folder = new File(path);
File[] listOfFiles = folder.listFiles(); 
for (int i = 0; i < listOfFiles.length; i++) {
    // Do something with "listOfFiles[i]"
}

UPDATE

To list the files recursively, your best approach is fairly easy:

  • Create a queue of directories. Initially add the first directory to the queue
  • Pop the first directory element off the queue.
  • List all files in that directory, same as above
  • Iterate over all the files in that directory
  • If a file is a directory (use isDirectory() method), add it to the back of the queue. Else, process this next file as needed (e.g. print)
  • Stop when the queue is empty.

An example (I think a bit different from my approach above) is http://www.javapractices.com/topic/TopicAction.do?Id=68


Renaming a file

http://www.roseindia.net/java/example/java/io/RenameFileOrDir.shtml

    boolean Rename = oldfile.renameTo(newfile);

Finding a new name to rename to

I'm not sure what you want the formatting rules to be - when I implemented the same utility in Perl for my own use I used Regular Expressions. For Java, that'd be java.util.regex

DVK
Thanks! I found out how to do it recursively here: http://www.javapractices.com/topic/TopicAction.do?Id=68
Amir Rachum
@Amir - LOL... I added the same link as an example. I think my algo above might be a bit more straightforward to implement (I saw a very novice Java developer do it in several minutes)
DVK
+1  A: 

This Sun Totorial could be a good start. If I where you I would basically retrieve all the files in the directory and then loop through them, as shown here. You might have to use regular expressions as well, a basic tutorial can be found here

npinti
+1  A: 

You can always use the standard java.io.File class, but it's primitive and not very useful on its own.

For complex file-I/O operations, I recommend using Apache Commons IO, which provides a rich class library for (among other things) file operations. See classes like FileUtils and FilesystemUtils

skaffman