Files

     

The following class demonstrates several different methods of the java.io.File class. These include getting the size of a file, renaming a file, and moving a file to a different directory. It also gives you some utility methods to do things you might commonly need to do, such as get the file size in bytes.

CommonFileTasks.java

 

 package net.javagarage.demo.io.files; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; /**<p>  * This class demonstrates a number of  * typical things you need to do when working  * with files.  * </p>  * @author eben hewitt  * @see File, NumberFormat  **/ public class CommonFileTasks { private static final String ps = File.separator; //enum new in 5.0 classname //the values will be automatically populated in order //starting with 0 if you don't specify them public enum Size { BYTES, KILOBYTES, MEGABYTES; } public static void main(String[] args) { String aFile = "C:\mysql\bin\mysqld-nt.exe"; log(getFileSize(aFile, Size.BYTES)); log(getFileSize(aFile, Size.KILOBYTES)); log(getFileSize(aFile, Size.MEGABYTES)); String bFile = "C:\test.txt"; createFile(bFile); fileExists(bFile); renameFile(bFile, "C:\test2.txt"); deleteFile(bFile); moveFile("C:\test2.txt", "C:\backups\"); } /**  * Creates a file if it doesn't already exist.  * @param fileName Name of the file you want to create  */ public static void createFile(String fileName){ try{ File file = new File(fileName); //creates file boolean success = file.createNewFile(); if (success) { log("Created new File"); } else { log("File existed already. Not re-created."); } } catch (IOException e) { log(e.getMessage()); } } /**  * Renames a file. File will not be renamed if a file  * of the new name already exists in that directory.  * @param oldFile File to be renamed.  * @param newFile New name for the file.  */ public static void renameFile(String oldFile,        String newFile){ boolean success = new File(oldFile).renameTo(new File(newFile)); if (success) { log("File " + oldFile + " renamed to " + newFile); } else { log("File " + oldFile + " could not be renamed."); } } /**  * Moves a file to a different directory. Note that  * the default behavior is to fail if the directory  * to which you are moving the file does not already  * exist. Remember  * that creating a new File <i>object</i> does not  * create a new file <i>on disk</i>.  * <p>  * So this creates the directory if it doesn't exist.  * @param fileName Name of the file to be moved.  * @param destinationDir New location and name  * for the file.  */ public static void moveFile(String fileName, String destinationDir){ File f = new File(fileName); File dir = new File(destinationDir); if (! dir.exists()){ //creates any needed directories that don't exist dir.mkdirs(); } boolean success = f.renameTo(new File(new File(destinationDir), f.getName()));    if (success) {    log("File " + fileName + " moved to " +            destinationDir);    } else { log("File " + fileName + " could not be moved.");    } } /**  * Deletes a local file.  * @param fileName File to delete  */ public static void deleteFile(String fileName){ boolean success = (new File(fileName)).delete(); if (success) { log(fileName + " deleted."); } else{ log(fileName + " could not be deleted."); } } /**  * Tests whether the file or directory exists already.  * @param fileName The file to check.  */ public static void fileExists(String fileName){ boolean exists = (new File(fileName)).exists(); if (exists) { log("File " + fileName + " exists."); } else { log("File " + fileName + " does not exist."); } } /**  * file.length() returns a long representing the  * file size in bytes. This makes it a little more  * convenient to work with.  */ public static String getFileSize(String           fileName, Size s){ File file = new File(fileName);     switch (s) {     default:     case BYTES:        return file.length() + " bytes";     case KILOBYTES:        return file.length() / 1024 + " KB"; case MEGABYTES:     double size = new Double(file.length() /                            1024).doubleValue() /1024; //create a display format for the number //make it have two decimal places NumberFormat formatter = new DecimalFormat("#.##"); return formatter.format(size) + "MB"; }     } private static void log(String msg){ System.out.println(">" + msg); } } 

The output is like this:

 

 >2248704 bytes >2196 KB >2.14MB >Created new File >File C:\test.txt exists. >File C:\test.txt renamed to C:\test2.txt >C:\test.txt could not be deleted. >File C:\test2.txt could not be moved. 

Useful Methods

The java.io.File class includes a number of methods that make it easy to work with files. For the examples that follow, assume I've got a file on my hard drive at C:\\backups\\test2.txt that we'll use to compare the results of the following methods.

Here they are:

  • boolean delete() Deletes a file

  • boolean exists() Returns whether the file denoted by this pathname exists

  • File getAbsoluteFile() Gets the file name in absolute form: C:\backups\test2.txt

  • File getCanonicalFile() Gets the file name in canonical form: C:\backups\test2.txt

  • String getParent() Gets the pathname of the parent directory of this file: C:\backups

  • boolean isDirectory() Whether the current file is a directory

  • boolean isFile() Whether the current file is a file

  • boolean isHidden() Whether the current file is marked hidden

  • boolean renameTo(File newName) Renames the file on which the method is called to the newName

  • boolean setLastModified(long time) Sets the date and time of when this file was last modified

  • URI toURI() Makes a URI object of this file: file:/C:/backups/test2.txt

  • URL toURL() Makes a URL object of this file: file:/C:/backups/test2.txt

Note that use of some of the preceding methods (in particular toURL() and getCanonical-File() require you to handle the checked exception IOException ).

Traversing Directories and Files

This is a class you can easily transfer directly into your projects. It features a method for recursively visiting a directory tree and all of the files in it. There is a method called execute that simply writes out directory names in all caps and indents file names under the directory in which they live. You can easily modify that method to do whatever kind of processing you want (for instance, make it all read only, set the last modified date, whatever). Here it is.

TraverseDirs.java
 

 /* This class lists all of the directories and files under a specified start directory. The method "execute" here simply prints out info about the dir. You could change the execute method to do something more exciting. */ package net.javagarage.demo.io.dir; import java.io.File; public class TraverseDirs { private static final String startDir = "C:\eclipse21\workspace\dev\WEBINF\ src\net\javagarage\demo\io"; public static void main(String [] arg){ //specify the dir to start in //and list everything under it listEachDirAndFile(new File(startDir)); }    //iterate all files and directories under dir       public static void listEachDirAndFile(File dir) {          execute(dir);          if (dir.isDirectory()) {             String[] sub = dir.list();             for (int i=0; i< sub.length; i++) {                listEachDirAndFile(new File(dir, sub[i]));             }       }    }    //iterate only directories under dir (recursive call)    public static void listDirs(File dir) {       if (dir.isDirectory()) {          execute(dir);          String[] subDirs = dir.list();          for (int i=0; i < subDirs.length; i++) {             listDirs(new File(dir, subDirs[i]));          }       }    }    //iterate files in each dir (recursive call)    public static void listFiles(File dir) {       if (dir.isDirectory()) {          String[] sub = dir.list();          for (int i=0; i < sub.length; i++) {             listFiles(new File(dir, sub[i]));          }       } else {          execute(dir);       }    } //this is just where you do whatever work //you want to do with each file or dir public static void execute(File f){ if (f.isFile()){ System.out.println("\t" + f.getName()); } else { System.out.println("Dir: " + f.getName().toUpperCase()); } } } 

For me, the output is like this:

 

 Dir: IO Dir: DIR TraverseDirs.class TraverseDirs.java Dir: FILES CommonDirectoryTasks.java CommonFileTasks$Size.class CommonFileTasks.class CommonFileTasks.java WriteBytes.java 

Notice that the CommonFileTasks$Size.class represents the enum Size, and the IO directory is empty.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net