Tuesday, January 28, 2014

File I/O - File class

Applications often interact with the filesystem to output data to and/or input data from files.

Java's standard class library supports filesystem access via its,

  • class File
  • class RandomAccessFile
  • stream
  • writer/reader APIs
Please note that, it’s preferred to access file systems via Java’s New I/O APIs. But you should also know about classic I/O APIs because you’ll encounter them while modifying legacy code that uses classic I/O.

Note: New I/O APIs will be discussed in another blog post.

Reference: http://www.mkyong.com/tutorials/java-io-tutorials/

File

Applications often interact with a filesystem, which is usually expressed as a hierarchy of files and directories starting from a root directory.

Windows and other platforms on which a Java Virtual Machine (JVM) runs typically support at least one filesystem. 

Ex: Unix or Linux platform combines all mounted (attached and prepared) disks into one virtual filesystem.
In contrast, Windows associates a separate filesystem with each active disk drive.

Note: The set of available filesystem roots is affected by various platform-level operations, such as inserting or ejecting removable media, and disconnecting or unmounting physical or virtual disk drives.

Getting filesystem roots

Listing. Dumping available filesystem roots to the standard output device
import java.io.File;

class DumpRoots
{
   public static void main(String[] args)
   {
      
File[] roots = File.listRoots();
      for (File root: roots)
         System.out.println(root);
   }
}

When I run this application on my Windows XP platform, I receive the following output, which reveals four available roots:
A:\
C:\
D:\
E:\
If I ran DumpRoots on a Unix or Linux platform, I would receive one output line consisting of the virtual filesystem root (/).
Getting file instance
Obtain a File instance by calling a File constructor such as File(String pathname), which creates a File instance that stores the pathname string.
File file1 = new File("/x/y"); // on unix or linux platform
File file2 = new File("C:\\temp\\x.dat"); // on windows platform
Note: path is a hierarchy of directories that must be traversed to locate a file or a directory. A pathname is a string representation of a path; a platform-dependent separator character(such as the Windows backslash [\] character) appears between consecutive names.
Caution Always double backslash characters that appear in a string literal, especially when specifying a pathname; otherwise, you run the risk of bugs or compiler error messages.
Each of above example file instances use absolute pathname, which is a pathname that starts with the root directory symbol; no other information is required to locate the file/directory.
  • The java.io package’s classes default to resolving relative pathnames against the current user (also known as working) directory.
  • Default current user working directory is identified by system property user.dir
  • The default name-separator character is from system property file.separator, and is also stored in File's separator and separatorChar class fields.
File offers additional constructors for instantiating this class:
  • File(String parent, String child) creates a new File instance from
    parent pathname string and a child pathname string.
  • File(File parent, String child) creates a new File instance from a parent pathname File instance and a child pathname string.


import java.io.File;
import java.io.IOException;
class FileOperations
{
       public static void main(String[] args) throws IOException
      {
            File file = new File("test.txt");
            file.createNewFile();
            File f1 = file.getAbsoluteFile();
            String str = File.separator;
          
  System.out.println("File separator= "+str);
            System.out.println("File= "+file);
            System.out.println("f1 Absolute File= "+f1.getAbsolutePath());
            System.out.println("Absolute File= "+file.getAbsoluteFile());
            System.out.println("Absolute path = "+file.getAbsolutePath());
            System.out.println("Canonical path = "+file.getCanonicalPath());
            System.out.println("Name = "+file.getName());
            System.out.println("Parent = "+file.getParent());
            System.out.println("Path = "+file.getPath());
            System.out.println("Is absolute = "+file.isAbsolute());
      }
}

Output:
File separator= \
File= test.txt
f1 Absolute File= D:\MyJavaLearning\HelloWorld\test.txt
Absolute File= D:\MyJavaLearning\HelloWorld\test.txt
Absolute path = D:\MyJavaLearning\HelloWorld\test.txt
Canonical path = D:\MyJavaLearning\HelloWorld\test.txt
Name = test.txt
Parent = null
Path = test.txt
Is absolute = false


 
Note Java 6 added long getFreeSpace()long getTotalSpace(), and long getUsableSpace() methods to File that return disk space information about the partition.

File declares five methods that return the names of files and directories located in the directory identified by a File object’s abstract pathname.

List all the files and folders from a directory(not recursive)


  /**
     * List all the files and folders from a directory
     * @param directoryName to be listed
     */
    public void listFilesAndFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            System.out.println(file.getName());
        }
    }

List all the files from a directory


/**
     * List all the files under a directory
     * @param directoryName to be listed
     */
    public void listFiles(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }

List all the folders from a directory (not including recursive sub folders)
/**
     * List all the folder under a directory
     * @param directoryName to be listed
     */
    public void listFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isDirectory()){
                System.out.println(file.getName());
            }
        }
    }

List all files from a directory and sub-directories (recursive)
    /**
     * List all files from a directory and its subdirectories
     * @param directoryName to be listed
     */
    public void listFilesAndFilesSubDirectories(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
        }
    }

Using FilenameFilter to filter listing of files
This following demo example filters all the files based on .txt extension.
import java.io.File;
import java.io.FilenameFilter;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File[] paths;
      
      try{      
         // new File instance, here we want to list files in directory c:\test
         f = new File("c:/test");
         
         // create new filename filter
         FilenameFilter fileNameFilter = new FilenameFilter() {
   
            @Override
            public boolean accept(File dir, String name) {
               if(name.lastIndexOf('.')>0)
               {
                  // get last index for '.' char
                  int lastIndex = name.lastIndexOf('.');
                  
                  // get extension
                  String str = name.substring(lastIndex);
                  
                  // match path name extension
                  if(str.equals(".txt"))
                  {
                     return true;
                  }
               }
               return false;
            }
         };
         // returns pathnames for files and directory
         paths = f.listFiles(fileNameFilter);
         
         // for each pathname in pathname array
         for(File path:paths)
         {
            // prints file and directory paths
            System.out.println(path);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}
File also declares several methods for creating files and manipulating existing files.

















Creating Temporary File
You can use the overloaded createTempFile() methods to create the temporary file. If you don’t specify a directory in which to store this file, it’s created in the directory identified by the java.io.tmpdir system property.
Listing . Experimenting with temporary files
import java.io.File;
import java.io.IOException;

class TempFileDemo
{
   public static void main(String[] args) throws IOException
   {
      System.out.println(System.getProperty("java.io.tmpdir"));
      File temp = File.createTempFile("text", ".txt");
      System.out.println(temp);
      temp.deleteOnExit();
   }
}
Output:
C:\DOCUME~1\JEFFFR~1\LOCALS~1\Temp\
C:\DOCUME~1\JEFFFR~1\LOCALS~1\Temp\text3436502412322813057.txt

You probably want to remove the temporary file after the user tells the application to save or discard the changes. The deleteOnExit() method lets you register a temporary file for deletion; it’s deleted when the JVM ends without a crash/power loss.
Finally, File implements the java.lang.Comparable interface’s compareTo() method, and overrides equals() and hashCode().

No comments:

Post a Comment