Introduction to programming in java

Introduction to programming in
java
Lecture 26
Writing in a file
PrintStream
• PrintStream is used for character output to a text file.
• Here is a program that creates the file myOutput.txt
and writes several lines of characters to that file.
PrintStream (Cont…)
• The program first creates a File object that
represents the disk file.
File file = new File( "myOutput.txt" );
• Next the program connects the file to an output
PrintStream.
– If the file already exists its contents will be destroyed,
unless the user does not have permission to alter the file.
If this is the case, an IOException will be thrown and the
program will end.
PrintStream print = new PrintStream( file );
PrintStream (Cont…)
• Several lines of characters are sent to the
output stream (and to the file). Each line ends
with the control characters that separate lines:
print.println( "The world is so full" );
print.println( "Of a number of things," );
print.println( "I'm sure we should all" );
print.println( "Be as happy as kings." );
PrintStream (Cont…)
• Finally, the stream is closed. This means that
the disk file is completed and now is available
for other programs to use.
print.close();
• The file would be closed when the program
ended without using the close() method. But
sometimes you want to close a file before
your program ends.
Example
Practice Question # 1
• Write a program which copies all the contents
of one file and save it into another file.
Provide the name of input and output file
names using command line arguments.
• Example
> java MyCopyFileProgram inputData.txt outputData.txt
Practice Question # 2
• Write a program which takes integer values
from one file. Calculate the square of each
integer value and save results in an other file.
Ask the user to provide the names of input
and output files.
Practice Question # 3
• Write a program that reads integers from a
text file. The program writes out the positive
integers in the input file to one output file and
the negative integers to a second output file.
Prompt the user for the names of all three
files.