Java-Input Output
Java-Input Output
Notes from
Well House
Consultants
These notes are written by Well House Consultants and distributed
under their Open Training Notes License. If a copy of this license is not
supplied at the end of these notes, please visit
http://www.wellho.net/net/whcotnl.html
for details.
Well House Consultants provides niche training, primarily but not exclusively in
Open Source programming languages. We offer public courses at our training centre
and private courses at your offices. We also make some of our training notes available
under our "Open Training Notes" license, such as we’re doing in this document here.
You are NOT allowed to charge (directly or indirectly) for the copying or distribu-
tion of these notes, nor are you allowed to charge for presentations making any use
of them.
If you would like us to attend a course (Java, Perl, Python, PHP, Tcl/Tk, MySQL
or Linux) presented by the author of these notes, please see our public course
schedule at
http://www.wellho.net/course/index.html
If you have a group of 4 or more trainees who require the same course at the same
time, it will cost you less to have us run a private course for you. Please visit our onsite
training page at
http://www.wellho.net/course/otc.html
which will give you details and costing information
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Writing to a file. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Formatted output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1 Overview
For output so far, we have used the System.out.print method and its brother
System.out.println . There are many more ways of doing output, including a
huge selection in the java.io package.
For input, we have used the wellreader class specially provided for this course. You
may wonder why we haven’t even shown you one standard input class (yes, there are
many).
• Input is very error prone
• If you ask for a number, your user is very likely to provide text, or an incorrect
format, or an end-of-file
And so all the input routines provided as a standard part of the Java libraries
include exceptions. You need to try and catch , if necessary, in almost every
circumstance!
However, you are now familiar with exceptions, so let’s have a look at the wellreader
class ...
2.2 The Wellreader class
// Well House Consultants,
2004.
import java.util.*;
import java.io.*;
Hmm. There are still a number of other new things there, though you will have
worked out by now that if the wellreader class has any problem reading a number, it
simply returns a zero!
2.3 Input/output from basics
You may want to input and output to and from a number of sources and destina-
tions. Output could be to ...
• Text to the current window
• A device, such as a tape drive or printer
• The input channel of another process on the same system
• The input channel of a process on another system
And the output could be either direct from your application or to your shell, which
in turn could output to most of those devices.
}
}
Our Filewriter object is in fact implemented as a file on the file system, which is
opened by the successful calling of the constructor method since this is a character
rather than a byte stream.
In other words, after this line has been executed, a file called abc.123 has been
created which we can write to via the demofile object. Let’s go on and do so!!
We can write to the file using the write method:
demofile.write("card number "+(k+1)+" is ");
demofile.write(play[k].getcardname()+"\n");
which is, in fact, defined in the superclass. In other words, although we are writing
to file here, the method would work just as well on other output streams such as:
• StringWriter
• CharArrayWriter
• PipeWriter
which write to a character string, a character array, and a pipe to another process,
respectively.
The method also works to output streams:
• BufferedWriter
• FilterWriter
which are actually extra streams that fit between the application and the file, buff-
ering (for efficiency) or filtering / converting data.
OK, this is getting a bit exotic, but it does give you some idea of the flexibility!
We’ll come back to that later.
And when we have finished writing to the file, we close it with
demofile.close();
Let’s look at some more mundane things associated with files, the bread and butter
into which we can put our fancy kangaroo meat and sweetcorn filling, later.
The areas we should look at include:
• Ensuring that we can create the file and that it creates correctly and that there is
enough disc space
• Ensuring that we are not overwriting an existing file
• Ensuring that the write operations work
• More flexibility in how we write to the file, and indeed on how we write to the
screen! To come up with tabular data, for example, would be a nightmare in what
you have seen so far!
Let’s start with the opening of the file and checking it.
Actually, in our broughton.java example we did have to make one consideration of
error conditions. If you compile it with just the open/write/close sequence added
from the previous example, you’ll get the error message:
And in our example, the author cheated by just passing up the exception to the
calling class, changing:
public static void main(String[] args)
to:
public static void main(String[] args)
throws IOException
if (! demofile.exists())
{
FileWriter demo = new FileWriter(demofile);
demo.write
("// File created by Java Class winsley\n");
demo.close();
}
else
{
System.out.print
("Sorry - file already exists\n");
long how_big = demofile.length();
System.out.println("length "+how_big);
}
We have created an object of class File which we have then examined with the
exists method to ensure that we do not overwrite an existing file.
Note that creating a File object does not itself create or open a file. The file is still
created/opened by the FileWriter method.
We can use our File object to learn more about our file using other class methods.
In our example, we have chosen to report on the length of the file.
{
public static void main(String[] args)
throws IOException
{
String inline;
File demofile = new File("abc.txt");
if (demofile.exists())
{
System.out.print
("Sorry - file already exists\n");
System.exit(1);
}
1
it is also possible to specify a filter
Here are some examples of what is printed when we apply the format (we’ll show
you the actual code in a page or two):
-58.0 degrees F
-56.2 degrees F
-54.39 degrees F
-0.39 degrees F
+1.4 degrees F
+32.0 degrees F
+212.0 degrees F
The ";" in the format indicates that we are providing separate formats for positive
and negative numbers; nothing so simple as an automatic minus sign as we had in
the last example!
Positive numbers, described first:
• Show a single leading zero if they are less than one degree
• Have a comma separator every two digits (yes, we know the usual thing would be
every three digits)
• Always show exactly two figures after the decimal point, even if they are both zero
for (temper=lower;
temper<=upper;
temper += (upper-lower)/steps)
{
tstring = centFormat.format(temper);
destiny.write(tstring);
faren = temper / 5.0 * 9.0 + 32.0;
tstring = farFormat.format(faren);
destiny.write(" converts to "+tstring+"\n");
}
Exercise
Extend your program from the previous example to read four integer values and write them out to a file.
If the file already exists, flag that fact before you even start, and exit.
Sample
if (! demofile.exists())
{
FileWriter demo = new FileWriter(demofile);
demo.write
("// File created by Java Class winsley\n");
demo.close();
}
else
{
FileReader demo = new FileReader(demofile);
int inchar = -1;
for (int k=0;k<10;k++)
{
inchar = demo.read();
if (inchar >= 0) System.out.print(" "+inchar);
}
if (inchar < 0)
System.out.print(" End-of-file");
System.out.print("\n");
}
We use the same object of class File. After all, at this point we don’t know whether
we’re going to be writing to or reading from the file in this paticular example!
Once we know that the file exists, we choose to read it; we must open it for reading
by creating a FileReader object for it.
The most basic method of reading a file is the read method (specified without
arguments) which reads one character at a time and passes each back to us as an
integer. A -1 is returned if we have read to the end of the stream. Thus, to read up
to 10 characters and display their integer values:
seal% od -c fred
0000000 / / F i l e \n
0000010
seal% od -c bradley.class | head -3
0000000 312 376 272 276 \0 003 \0 - \0 p \b \0 : \b \0 ;
0000020 \b \0 < \b \0 H \b \0 M \b \0 R \b \0 X 007
0000040 \0 U 007 \0 [ 007 \0 \ 007 \0 ] 007 \0 ^ 007 \0
seal%
You can do anything reading character-by-character ... but you have to do it. All
the data manipulation must be elsewhere in your Java program, be it in your main
method or in other methods you call!
The read method does also support reading into a character array. It reads up to
the length of the array and returns the number of characters actually read. Thus:
1
although notice that it’s dangerous to print out the character array because it may contain any number of non-
printable characters
will contain ASCII text, separated into lines with a particular delimiter.
Our base FileReader class does not provide a method for reading line-by-line, but
BufferedReader does:
BufferedReader demo = new BufferedReader(
new FileReader(demofile));
for (int k=0;k<10;k++)
{
String next_line = demo.readLine();
System.out.println(next_line);
}
try{
BufferedReader standard = new BufferedReader(
new InputStreamReader(System.in));
inline = standard.readLine();
}
catch (Throwable e)
{
System.out.print("data entry error");
System.out.println(e);
return ;
}
File demofile = new File(inline);
if (! demofile.exists())
{
FileWriter demo = new FileWriter(demofile);
demo.write("// File created by Java Class winsley\n");
demo.close();
}
else
{
BufferedReader demo = new BufferedReader(
new FileReader(demofile));
for (int k=0;k<10;k++)
{
String next_line = demo.readLine();
System.out.println(next_line);
}
}
}
}
Exercise
Take the example program Javafgrep.java from the course server and work out what it does. Modify it so that it always reads
the data from a file named stdcodes.xyz, and further modify it to report on the total number of lines on the input file.
Write a Java program which creates a file called "my.txt". Into that file, write the names of all the files in the current directory
that end in ".java", and the first line of each of those file.
License
These notes are distributed under the Well House Consultants
Open Training Notes License. Basically, if you distribute it and use it
for free, we’ll let you have it for free. If you charge for its distribution of
use, we’ll charge.
Please send any amendments and corrections to these notes to the Copyright
holder - under the spirit of the Open Distribution license, we will incorporate suit-
able changes into future releases for the use of the community.
If you are charged for this material, or for presentation of a course (Other than by
Well House Consultants) using this material, please let us know. It is a violation of
the license under which this notes are distributed for such a charge to be made,
except by the Copyright Holder.
If you would like Well House Consultants to use this material to present a training
course for your organisation, or if you wish to attend a public course is one is avail-
able, please contact us or see our web site - http://www.wellho.net - for further
details.
Change log
Original Version, Well House Consultants, 2004
License Ends.