4.1. Java Text Files.   

Our Java programs are files - files of characters. Any program or text we create with an editor such as ed or vi, is a file of characters.

So far we have been using the standard default files input and output.
eg static PrintStream output = System.out;
static ASCIIInputStream input = new ASCIIInputStream(System.in);

To access these default files we used the following pre- defined Java class methods:

     readInt()        readDouble()

Format.print() println()


Note that any Java data type which can be read from input or written to output can also be read from or written to a text file.

Java provides other pre-defined methods1 for use with text files: (See footnote)

bad()

Determines if a previous ASCII I/O operation caused an
error.
eof()
Determines if a previous ASCII I/O operation caught End Of
File.
flushLine()
Causes the next I/O operation to start at the beginning of
the next input line.
read(byte[])
Reads data into an array of bytes.
read(byte[], int, int)
Reads data into an array of bytes.
readBoolean()
Reads an ASCII boolean value.
readByte()
Reads a single byte.
readChar()
Read an ASCII character and convert it into the internal
char format.
readDouble()
Reads an ASCII decimal floating point number.
readFloat()
Reads an ASCII decimal floating point number.
readFully(byte[])
Reads bytes, blocking until all bytes are read.
readFully(byte[], int, int)
Reads bytes, blocking until all bytes are read.
readInt()
Reads an ASCII decimal integer.
readLine()
Reads in a line that has been terminated by a \n, \r, \r\n or
EOF.
readLong()
Reads an ASCII decimal long.
readShort()
Reads an ASCII decimal short.
readUnsignedByte()
Reads a single unsigned byte.
readUnsignedShort()
Reads an ASCII decimal unsigned short.
readUTF()
Does nothing.
readWord()
Reads a word.
skipBytes(int)
Skips bytes, block until all bytes are skipped.

4.1.1. Declaring text files   

We are familiar with the declaration of input and output:

 import java.lang.*;

import local.units.sdsu.io.*;
import java.io.*;
:
static PrintStream output = System.out;
static ASCIIInputStream input = new ASCIIInputStream(System.in);

The import statements let us use the ASCIIInputStream class which lets us do easy input/output. We create an ASCII Input Stream from the operating systems standard input.


Similarly we create a PrintStream from the operating systems standard output. To use files instead we can:

 import java.lang.*;

import local.units.sdsu.io.*;
import java.io.*;
:
static PrintStream fileoutput ;
static ASCIIInputStream fileinput ;
public static void main(String argv[]) throws IOException
:
FileOutputStream out_stream= new FileOutputStream("fred.dat"); // Get a FileOutputStream object
fileoutput = new PrintStream(out_stream); // Use it to create new file stream
FileInputStream in_stream = new FileInputStream("freda.dat"); // Get a FileInputStream object
fileinput = new ASCIIInputStream(in_stream); // Use it to open an existing file

Note that we can now use fileoutput and fileinput just as we used input and output. We can declare and create as many of these input and output streams as we like. We can then use any of the methods of these classes or their superclasses.

Example : Copy one file to another -

import java.lang.*;

import local.units.sdsu.io.*;
import java.io.*;
public class Copy3
{
static PrintStream fileoutput ;
static ASCIIInputStream fileinput ;
public static void main(String[] argv)
throws FileNotFoundException, IOException
{
if (argv.length != 2)
System.err.println(
"Usage: java FileCopy <source file> <destination file>");
else
{
FileInputStream in_stream = new FileInputStream(argv[0]); // Get a FileInputStream object
fileinput = new ASCIIInputStream(in_stream); // Use it to open an existing file
FileOutputStream out_stream= new FileOutputStream(argv[1]); // Get a FileOutputStream object
fileoutput = new PrintStream(out_stream); // Use it to create new file stream
for(;;)
{
char ch;
ch = fileinput.readChar();
if(fileinput.eof())
break;
Format.print(fileoutput,"%c",ch);
}
fileoutput.close();
fileinput.close();
}
}
}


It is possible for you to grab the source code and compile it on your machine via
After retrieving and saving the code, you should be able to type:
javac Copy.java ; java Copy
This will execute the code. People not at Curtin will need to setup their Java environment first.

A more robust solution lies with the use of the File class. This class lets us check various attributes of the named file before we try to open or create it. For example, does the file exist?, is it writable?, etc. We can also copy the file in large chunks of bytes not character by character. A true file copy would not worry about each individual character - in fact it would not worry about the structure of the file at all - it would just copy all bytes in the file to the new file.

The following example illustrates the use of the File class:

import java.io.*;

public class FullCopy
{
public static void copy(String source_name, String destination_name) throws IOException
{
File source_file = new File(source_name); File destination_file = new File(destination_name);
FileInputStream source = null; FileOutputStream destination = null;
byte[] buffer = new byte[1024];
int bytes_read;
try
{ // First make sure the specified files exist, are files, and are readable.
if (!source_file.exists() || !source_file.isFile())
throw new IOException("Copy: no such file: " + source_name);
if (!source_file.canRead())
throw new IOException("Copy: source file is unreadable: " + source_name);
if (destination_file.exists())
{
if (!destination_file.isFile())
throw new IOException("Copy: destination is not a file: " + destination_name);
if (!destination_file.canWrite())
throw new IOException("Copy: destination file is unwriteable: " + destination_name);
}
source = new FileInputStream(source_file);
destination = new FileOutputStream(destination_file);
// Now copy the file.
while((bytes_read = source.read(buffer)) != -1)
destination.write(buffer, 0, bytes_read);
}
finally
{
if (source != null)
try source.close();
catch (IOException e) ;
if (destination != null)
try destination.close();
catch (IOException e) ;
}
}
public static void main(String[] argv)
{
if (argv.length != 2) System.err.println( "Usage: java FileCopy <source file> <destination file>");
else
{
try
copy(argv[0], argv[1]);
catch (IOException e)
System.err.println(e.getMessage());
}
}
}


It is possible for you to grab the source code and compile it on your machine via
After retrieving and saving the code, you should be able to type:
javac FullCopy.java ; java FullCopy
This will execute the code. People not at Curtin will need to setup their Java environment first.