Monday, February 13, 2012

The java.io.File class

Programs are required to write and read data to and from external sources - such as files, other programs, or network resources.

The Java Input/Output (I/O) package - java.io - enables Java programs to read and write data in various formats. Text, sound, graphics, and video files can be processed by appropriate classes from the java.io package.
The java.io package contains classes that enable you to access data both sequentially and at random.

Note

In sequential data access, data is read or written in sequence, from the first record to the last. Nonsequential or random - data access involves reading or writing data in a random order.
The Reader and Writer classes, and their various subclasses, are used for sequential data access. These classes input or output data sequentially as ordered streams of bytes.

The RandomAccessFile class and its subclasses are used to input or output data in a file. The bytes do not need to be in ordered sequences, as opposed to a stream.
The java.io.File class represents either a directory or a single file within the file system.It allows you to navigate, describe, and access those files or directories.
The Java security manager allows only specified operations to be performed within a given security context. Because most browsers don't allow any kind of file access, the File class and related I/O classes are usually used in applications instead of applets.
Creating a File object does not necessarily mean that you create a real file or directory. While representing the name of a file, the File object does not represent, or enable you to access, the data in the file.

Similarly, when a File object is deleted by the garbage collector, no physical files are deleted.
Creating a File object does not actually create a file on the local system. It merely encapsulates the specified string in one of a number of constructors:
  • File (File directoryObj, String fileName)
  • File (String pathName)
  • File (String pathName, String fileName)
File (File directoryObj, String fileName)
This constructor creates a new File instance using the pathname from an existing File instance and a string containing the filename.
File (String pathName)
This constructor creates a new File instance using the given pathname string.
File (String pathName, String fileName)
This constructor creates a new File instance using the given pathname string and filename string.
Consider the code that creates a simple file access application in Java. To access a file, you should first import the relevant Java classes – in this case File and RandomAccessFile, which are both part of the java.io package.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SampleWriteFile implements ActionListener {"
The java.awt , java.awt.event, and javax.swing packages are imported to be able to utilize GUI components.
Once you have imported the relevant java.io classes, you need to instantiate the GUI components to be able to input names. These names are written to a RandomAccessFile named sampletext.txt.
public class SampleWriteFile  implements ActionListener {

  private Frame f;
  private Button write, clear, exit;
  private TextField txt;
  public SampleWriteFile(String s) {
    f=new Frame(s);
    write=new Button("Write to file");  write.addActionListener(this);
    clear=new Button("Clear entries");  clear.addActionListener(this);
    exit=new Button("Exit");  exit.addActionListener(this);
    txt=new TextField(20);  
    Label l=new Label("Enter name");
    Panel p=new Panel();
    Panel p2=new Panel();
    p.add(l);p.add(txt);
    p2.add(write);p2.add(clear);p2.add(exit);
    f.add(p, "North");
    f.add(p2);
    f.pack();
    f.setResizable(false); f.setVisible(true);  
  } 
In the RandomAccessFile instantiation, the rw option is used to be able to read and write data from the file.
public void writeFile() {
       try {
  RandomAccessFile file=new RandomAccessFile("sampletext.txt", "rw");
  file.seek(file.length());
  file.writeBytes(txt.getText()+ "\n");
      }
      catch(IOException e) {
  JOptionPane.showMessageDialog(null,"Cannot write to File","Exception",JOptionPane.ERROR_MESSAGE);
}
The seek method is used to get to a specific location in the file. The value returned by the length method is passed to the seek method, so that we can get to the end of the specified file.
The writeBytes method is used to write data coming from the text field into the file named SampleText.txt.

Supplement

Selecting the link title opens the resource in a new browser window.
View the code for the SampleWriteFile application.
There are 12 methods you can use on a File object. These include
  • exists
  • getName
  • getAbsolutePath
  • isDirectory
  • isFile
  • canRead
exists
You use the exists method to confirm whether a specified file exists. The method returns a value of true if the file exists.
getName
You use the getName method to return the name of a file or directory - the last element of a full pathname.
getAbsolutePath
The getAbsolutePath method returns a String value, which is the full absolute path to a file or directory, whether the file was initially constructed using a relative pathname or not.
isDirectory
The isDirectory method returns a value of true if the string specified in the object's constructor represents a directory instead of a file.
isFile
The isFile method determines whether a File object represents a file or a directory. The method returns a boolean value of true if an abstract filename exists, and is a normal file - that is, the File object does not represent a directory. Otherwise it returns false. The MS Windows implementation of the isFile method has been reworked in JDK1.6. It is now always set to return false for devices such as CON, NUL, AUX, LPT, which makes it consistent with the UNIX implementation of isFile.
canRead
The canRead method determines whether data can be read from a file. It returns a boolean value of true only if the file exists and can be read by the application. Otherwise it returns false.
The remaining six methods are
  • getTotalspace
  • getFreespace
  • getUsablespace
  • setWritable
  • setExecutable
  • canExecute
getTotalspace
The getTotalspace method returns a long value representing the size in bytes of the partition named by the abstract path.
getFreespace
The getFreespace method returns a long value, which is the number of bytes available on the partition named by the abstract path. The value returned is a hint, and not a guarantee that all the bytes are usable. The number of unallocated bytes are most likely accurate after the call to gerFreespace. This method does not guarantee that write operations to the file system are successful.
getUsablespace
The getUsablespace method returns a long value, which is the number of bytes available on the partition named by the abstract path name.
setWritable
The setWritable method allows a particular file to be writeable and takes two parameters. The first parameter is a boolean value. If set to true, the file becomes writable, but if set to false, the file becomes read only. The second parameter is also a boolean value. If set to true, the write permission applies only to the owner or the creator of the file, but if set to false, the write permission applies to everybody.
setExecutable
The setExecutable method sets the execute permission of a file. It also takes two parameters. If the first parameter is set to true, the file is set to allow execute operations. If the second parameter is set to true, the execute permissions apply only to the owner or the creator of the file. If the second parameter is set to false, the execute permission is applied to everybody.
canExecute
The canExecute method returns a boolean value. If true is returned, the file can be executed.
Consider the code that uses the isDirectory method to determine whether an array element - a File instance - is a directory. If it is, the application searches it for a specified file.
class InnerActionListener implements
  ActionListener {
    public void actionPerformed (ActionEvent e) {
      ReportAction r = new ReportAction() ;                  
      r.setPriority(Math.min(r.getPriority() + 1,
            Thread.MAX_PRIORITY));
      r.start() ;
      
      File[] allDrives = File.listRoots();
      for (int i=1 ; i<allDrives.length-1; i++) {
              if (allDrives[i].isDirectory())
        answer.append (search(allDrives[i], "test.txt"));
      }
      r.interrupt() ;
    }
}
Suppose you want to create an instance of a File and use the most common methods associated with a File class. This application searches for files using a method that takes a File object and a search string as parameters. The File object represents the directory being searched.
String search (File f, String fileName) {
  String contents[] = f.list() ;
  int i = 0;
  String found = "Not found" ;

  for (i=0; i<contents.length; i++) {
    if (fileName.equals (contents[i]))
      return (new File(f, contents[i]).getAbsolutePath()) ;
  }
  i = 0 ;
  while (i < contents.length) & (found.equals ("Not found"))) {
    File child = new File (f, contents[i]) ;
    if (child.isDirectory())
      found = search (child, fileName);
    i++ ;
  }    
  return found ;
}
Java uses the File object's list method to return an array of Strings, listing the contents of a directory. If the File does not represent a directory, the list method returns a null value. This will cause the application to throw a NUllPointerException, which can be handled by using a try-catch block.
If one of the files in the directory matches the filename specified by the user, the method returns a string, representing the absolute path to the target file.

2 comments:

Great article, thanks for sharing usefull information and i have seen more info onUI online training

This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again. The latest Tweets from Celebrity birthdays with 22 million users visit our website each month.

Post a Comment