20.Files and Streams

Monday, April 12, 2010 Posted by Sudarsan
Files and Streams

In some cases, data inputs are stored in files. Moreover, there are also instances when we want to store the output of a certain program to a file. In a computerized enrollment system, the student data that may be used as an input to the system is most probably stored in a particular file.

Then, one possible output of the system is the information about the subjects enrolled in by the students. Again, the output in this case may preferably be stored in a file. As seen in this application, there is a need for reading from a file and writing to a file. You will learn about file input and output in this sect ion.

Input and output

The Java library classes for IO are divided by input and output, as you can see by looking at the online Java class hierarchy with your Web browser. By inheritance, all classes derived from InputStream have basic methods called read( ) for reading a single byte or array of bytes. Likewise, all classes derived from OutputStream have basic methods called write( ) for writing a single byte or array of bytes.

However, you won’t generally use these methods; they exist so more sophisticated classes can use them as they provide a more useful interface. Thus, you’ll rarely create your stream object by using a single class, but instead will layer multiple objects together to provide your desired functionality. The fact that you create more than one object to create a single resulting stream is the primary reason that Java’s stream library is confusing.

It’s helpful to categorize the classes by their functionality. The library designers started by deciding that all classes that had anything to do with input would be inherited from InputStream and all classes that were associated with output would be inherited from OutputStream..

Types of InputStream

InputStream’s job is to represent classes that produce input from different sources. These sources can be (and each has an associated subclass of InputStream):

1. An array of bytes

2. A String object

3. A file

4. A “pipe,” which works like a physical pipe: you put things in one end and they come out the other

5. A sequence of other streams, so you can collect them together into a single stream

6. Other sources, such as an Internet connection.

In addition, the FilterInputStream is also a type of InputStream, to provide a base class for "decorator" classes that attach attributes or useful interfaces to input streams.


The File class

The File class has a deceiving name – you might think it refers to a file, but it doesn’t. It can represent either the name of a particular file or the names of a set of files in a directory. If it’s a set of files, you can ask for the set with the list( ) method, and this returns an array of String.

It makes sense to return an array rather than one of the flexible collection classes because the number of elements is fixed, and if you want a different directory listing you just create a different File object. In fact, “FilePath” would have been a better name. This section shows a complete example of the use of this class.

Creating File Objects

File objects are frequently used with objects of other java.io classes to specify files or directories to manipulate.

Class File provides four constructors. The constructor specifies the name of a file or directory to associate with the File object. The name contain path information as well as a file or directory.

public File(String name)

The constructor uses argument pathToName to locate the file or directory specified by name.

public File(String pathToName, String name)

The constructor uses an existing File object directory to locate the file or directory specified by name.

public File(File directory, String name)

The constructor uses the URI object to locate the file, which is used to locate web sites. For example, http://www.javacircuit.blogspot.com is the URL of javacircuit website.

public File(URI uri)


Now let’s move on to one example which demonstrates File class methods.


//File class and its Methods

package files;
// Inorder to use Streams we need to import the fallowing package
import java.io.*;


/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        File f=new File("D:\\BSNL.txt");
        
        getFile("File Name : "+f.getName());
        getFile("Path : "+f.getPath());
        getFile("Absolute Path: "+f.getAbsolutePath());
        getFile("Parent : "+f.getParent());
        getFile(f.exists() ? "File Exists" : "Does not exists");
        getFile(f.canWrite() ? "is Writable" : "Not Writable");
        getFile(f.canRead() ? "is readable" : "Not readable");
        getFile("is "+ (f.isDirectory() ? " " : "not" + "a directory"));
        getFile(f.isFile() ? "is normal File" :"Not a normal File");
        getFile("File Last Modified on" +f.lastModified() );
        getFile("File Size : "+f.length()+"bytes");
        
    }

    static void getFile(String s)
    {
        System.out.println(s);
    }
}

When we compile this program we can get the fallowing output

File Name : BSNL.txt
Path : D:\BSNL.txt
Absolute Path: D:\BSNL.txt
Parent : D:\
File Exists
is Writable
is readable
is nota directory
is normal File
File Last Modified on1243060523708
File Size : 192bytes


In order to use more methods of File class just go to java.io package in Java API.

In the next post we will discuss more about Files, that's all Folks !!!
  1. Anonymous

    vry gud......
    frm
    http://www.bhaica.com

Post a Comment