The Java Explorer Back | TOC | Next 

<Core><Intermediate><Advanced>
Overview | Packages | Class Internals | Collections | I-O | Network | Database 

The Javadoc documentation for the java.io package at Sun's Java site simply says:
Provides for system input and output through data streams, serialization and the file system. 

The java.io package
Don't be misled by the simple declaration above into believing that the java.io package is not too complicated. On the contrary, it is the most comprehensive in the java package hierarchy, and constitutes a forest of classes. But that is not a deterrent to the intrepid java explorer. We will begin very simply with files and file access for reading and writing.

File IO
For file manipulation Java provides the following classes:

The File class encapsulates file details such as size, last modified date and so on. It abstracts the semantics of a folder as well as a file. 

Listing 1
import java.io.File;    // for File I/O
import java.util.Date;    // for converting time in millis to date

public class FileDetails {

public FileDetails(String currentPath) {    // constructor

File path = new File(currentPath);        // create a file object
String[] files = path.list();                // Get list of file/folder objects

System.out.println("Name|Type|Modified|Size");
for(int i=0; i<files.length; i++) {
System.out.println();
File F = new File(files[i]);
System.out.print(F.getName());
String type = F.isDirectory()==true ? "Directory" : "File";
System.out.print("|"+type);
System.out.print("|"+new Date(F.lastModified()));
if(type.equals("File")) {
System.out.print("|"+F.length());
}
}
System.out.println("\nListed "+files.length+" objects");
}

public static void main(String[] args) {
new FileDetails(".");    // run against current directory
}
}


Listing 1 shows a program that captures the details of files and folders given a path - in this case, the path chosen is the current directory.

Here is the sample output:

Name|Type|Modified|Size

xml2html.java|File|Thu Dec 12 12:31:58 GMT+05:30 2002|729
stocks.xml|File|Sat Dec 07 15:32:22 GMT+05:30 2002|511
stocks.xsl|File|Sat Dec 07 15:32:44 GMT+05:30 2002|709
xml2html.class|File|Thu Dec 12 12:32:16 GMT+05:30 2002|1390
stocks.html|File|Sat Dec 07 15:34:54 GMT+05:30 2002|374
jstl_test.jsp|File|Tue Jan 07 16:43:12 GMT+05:30 2003|1168
spel.jsp|File|Tue Jan 07 16:34:56 GMT+05:30 2003|482
ejb|Directory|Sat Jan 18 09:26:46 GMT+05:30 2003
ant|Directory|Mon Jan 20 12:47:40 GMT+05:30 2003
jstl|Directory|Tue Jan 21 16:57:24 GMT+05:30 2003
jmail|Directory|Wed Jan 22 15:11:06 GMT+05:30 2003
collections|Directory|Mon Feb 03 12:12:52 GMT+05:30 2003
Calculator|Directory|Tue Feb 04 12:47:10 GMT+05:30 2003
FileDetails.java|File|Wed May 28 12:44:24 GMT+05:30 2003|754
FileDetails.class|File|Wed May 28 12:44:56 GMT+05:30 2003|1370
Listed 52 objects

The output list is truncated for reasons of space. The last two entries include the details of the file shown in Listing 1.

Some of the other nice things that you can do with the File object are:

For constraints of space and time, let's take leave of the File object, and poke around with reading and writing of files.

Before we look at the details of coding, we need to clear up a few things first. Like C++, Java handles input/output as streams. A data stream is a sequence of bytes or characters. Data is streamed from one system to another over a network, or within a system from one drive to another, or from the system console. The stream is either byte-oriented or character oriented. It is also possible to convert a byte stream to a character character stream through the use of a bridge class. The converted character stream may accept default platform encoding, or it may be set explicitly.

The byte streams are of three basic kinds:

There are of course several other classes to suit different needs, it will suffice to discuss these classes as an introduction to java.io package.

The byte streams are rooted at the abstract InputStream and OutputStream classes. The concrete subclasses do the actual job of data transfer. We will look at some code examples.

Listing 2
// Using FileInputStream and FileReader classes
import java.io.*;

public class FileStreamReader {

static String fileName = "FileStreamReader.java";

// Using InputStream
public FileStreamReader(FileInputStream fis) throws IOException {
byte[] bites = new byte[1024];
int bitesRead = fis.read(bites);
System.out.println(bitesRead + " bytes read.");
}

// Using Reader
public FileStreamReader(FileReader fr) throws IOException {
char[] chars = new char[1024];
int charsRead = fr.read(chars);
System.out.println(charsRead + " bytes read.");
}

public static void main(String[] args) {
// Using InputStream
try {
FileInputStream fin = new FileInputStream(fileName);
new FileStreamReader(fin);
fin.close();
} catch(IOException ioe) {
System.err.println("Error reading file");
}
// Using Reader
try {
FileReader fr = new FileReader(fileName);
new FileStreamReader(fr);
fr.close();
} catch(IOException ioe) {
System.err.println("Error reading file");
}
}
}

Output:
1005 bytes read.
1005 bytes read.

Listing 2 demonstrates the use of both the byte stream and character stream classes. A buffer is created to hold the bytes or chars as they are read one at a time, and at the end the count is output to console. It is more efficient to read a buffered input, however, and the following code snippet shows how-to. A buffered reader or input stream is used to read one line at a time.

BufferedReader br = new BufferedReader(new FileReader(fileName);
String line = br.readLine();

Ditto for BufferedInputStream. If you would experiment with Listing 2 above, just wrap the FileReader object inside the BufferedReader instance, and read off the lines one by one with the readLine() method. Output each line to console as you read.

while( (line=br.readLine()) != null)    // EOF condition
{
   System.out.println(line);
   line = br.readLine();
}

That's it. Now you know all you ever needed to know java IO basics. Armed with this information, you may enter the IO forest to further explore on your own.