[an error occurred while processing this directive]



Managing with the file system

How many times did you need to work with files in your Java applications? Reading and saving data to files is really easy using Java classes, expecially now that new functions and classes has been added with the Java 1.2. One of the problems you coul have to deal with, on Windows platforms, is how to know how many root directories (A:\, B:\, C:\, ...) are present on the system that is running your application. While on Unix/Linux operating system we have an unique root directory, Windows has different roots and this, sometimes, may be a problem. With Java 1.2 a new method has been added to the class File. It allows us to get the list of system's roots. On the other hand it is important to notice that this method, whose name is listRoots(), returns a string contining all roots avaiable on the system, including the "not ready" ones. With "not ready", I mean, as example, a drive with no disk. Be care with read only or access denied directories too. Additional informations about the current file system are obtained using other methods. The program we are going to write lists roots present on a Windows system using getRoots() method, and informs us about the ready and not ready ones. Look at the code below.




Import java.io.*;

public class SearchRoots {

public static void main (String args[])
{ File RootsList[] = File.listRoots();
for (k=0; k<RootsList.length; k++) { System.out.print ("Analizing "+RootsList[k]+". ");
if (RootsList.exists()) System.out.println (" Ready");
else System.out.println (" NOT ready.");
}
}

}



When we know which roots are present and ready on the system, it is possible to analyse their contents with list() method. list(), when applied to a directory, returns a File array, with the names of files and directories contained in the current directory. Then it is possible to move in the array applayng the isFile() and isDirectory() methods to each object. Then it is possible to process all the directories found using list() method again. It's easy, following this strategy, to implement a recursive procedure which analyses all the file system. Other methods could be useful to perform different operations on files. These are: getPath() wich returns the absolute path of a file object; exist() that verify if a particular file object exists; mkDir(), renameTo() e delete() whose task can be deduced from the functions' name.





Search thousands of newspapers, magazines!