In this tutorial, I take you through an important feature of Java: File Operations. We are going to take a look at Character and Byte Streams, some built-in Classes and their functionalities to be able to perform file operations. Then we are going to learn about a famous concept called exception handling. We are going to finalize this tutorial with Number Formatting.
Check out rest of the Tutorials: https://berksoysal.blogspot.com/2016/06/java-se-tutorials-basics-exercises.html
2. Java's IO package mostly concerns itself with the reading of
raw data from a source and writing of raw data to a
destination. The most typical sources and destinations of
data are these:
• Files
• Pipes
• Network Connections
• In-memory Buffers (e.g. arrays)
• System.in, System.out, System.error
2016 Winter
3. • IO Streams are a core concept in Java IO. A stream is a
conceptually endless flow of data.
• You can either read from a stream or write to a stream. A
stream is connected to a data source or a data
destination.
• Streams in Java IO can be either byte based (reading and
writing bytes) or character based (reading and writing
characters).
2016 Winter
4. • A program that needs to read data from some source
needs an InputStream or a Reader. A program that needs
to write data to some destination needs an OutputStream
or a Writer.
• InputStream
• OutputStream
• Reader
• Writer
}
}Character
Streams
Byte
Streams
2016 Winter
5. • Byte streams are associated with data-based (binary) I/O.
Examples of binary data include image and audio files, jpeg
and mp3 files for example.
•
• In Java, characters are encoded with Unicodes — character
streams are associated with text-based (human readable)
I/O. The character streams are called readers and writers as
I mentioned before.
• Java Character streams are used to perform input and
output for 16-bit unicode.
Folder Lab6 Lab6 Examples 01 Unicode.java
Java Byte streams are used to perform input and output
of 8-bit bytes.
2016 Winter
6. • You can get random access to files with Java IO via the
RandomAccessFile Class.
• Random access doesn't mean that you read or write from
truly random places. It just means that you can skip around
the file and read from or write to it at the same time in any
way you want. No particular access sequence is enforced.
• This makes it possible to overwrite parts of an existing file,
to append to it, delete from it, and of course read from the
file from wherever you need to read from it.
2016 Winter
7. • You can get random access to files with Java IO via the
RandomAccessFile Class.
• Random access doesn't mean that you read or write from
truly random places. It just means that you can skip around
the file and read from or write to it at the same time in any
way you want. No particular access sequence is enforced.
• This makes it possible to overwrite parts of an existing file,
to append to it, delete from it, and of course read from the
file from wherever you need to read from it.
2016 Winter
8. InputStream and OutputStream are two abstract classes that define the
methods that are common to all input and output streams.
The class InputStream declares the following three methods.
• int read(): Reads the next byte of data from the input stream. If no
byte is available, because the end of the stream has been reached, the
value −1 is returned;
• int read( byte[] b ): Reads some number of bytes from the input
stream and stores them into the buffer array b. The number of bytes actually
read is returned as an integer;
• close(): Closes this input stream and releases any system resources
associated with the stream.
Since InputStream is an abstract class it is never instantiated.
2016 Winter
9. The class OutputStream declares the following three methods.
• write(byte[] b): Writes b.length bytes from the specified byte array
to this output stream;
• flush(): Flushes this output stream and forces any buffered output
bytes to be written out;
• close(): Closes this output stream and releases any system resources
associated with the stream.
2016 Winter
11. Two objects are predefined and readily available for your
programs. System.in is an input stream associated with the
keyboard, and System.out is an output stream associated with
the console.
Remember ?
System.out.println(“Hello World”)
-----------------------------------
Scanner in = new Scanner(System.in);
String name = in.nextLine();
2016 Winter
12. Usually we follow 3 steps to write a file:
Opening a file.
Writing to that file.
Closing the file.
Closing the file is especially important since if the file
remains open, the internal and external resources remain
unavailable for other files.
2016 Winter
13. Reading from a file involves creating a FileInputStream object.
We’ll consider two constructors.
FileInputStream( String name ): This constructor receives the
name of the file as an argument. Example,
InputStream in = new FileInputStream( "data.txt" );
FileInputStream( File file ): This constructor receives a File
object as an argument, which is the representation of an
external file.
File f = new File( "data.txt" );
InputStream in = new FileInputStream( f );
2016 Winter
14. Because a FileInputStream allows to read bytes only, Java defines an
InputStreamReader as bridge from byte to character streams. Its usage is
as follows.
InputStreamReader in = new InputStreamReader(new
FileInputStream( "data.txt" ));
or
InputStreamReader in = new InputStreamReader( System.in );
• int read(): Reads a single character. Returns −1 if the end of stream has
been reached. The return type is int, the value −1 indicates the end-of-file
(eof). The value must be interpreted as a character, i.e. must be converted,
int i = in.read();
if ( i != -1 ) {
char c = (char) i;
}
Folder Lab6 Lab6 Examples 02 Keyboard.java
2016 Winter
15. • int read( char [] b ): Reads characters into an array. Returns the number
of characters read, or −1 if the end of the stream has been reached.
InputStreamReader in = new InputStreamReader(new
FileInputStream( "data.txt" ));
char[] buffer = new char[ 256 ];
num = in.read( buffer );
String str = new String( buffer );
2016 Winter
16. Write a class named Exercise1 that reads characters from
the keyboard using the method read( char[] b );
The maximum number of characters that can be read at a
time is fixed and determined by the size of the buffer.
Use the class Keyboard from the above example as a
starting point.
2016 Winter
17. For some applications, the input should be read one line at a
time. For this, you will be using an object of the class
BufferedReader.
A BufferedReader uses an InputStreamReader to read the
content.
The InputStreamReader uses an InputStream to read the raw
data. Each layer (object) adds new functionalities.
The InputStream reads the data (bytes).
The InputStreamReader converts the bytes to characters.
Finally, the BufferedReader regroups the characters into
groups, here lines.
2016 Winter
18. FileInputStream f = FileInputStream( "data.txt" );
InputStreamReader is = new InputStreamReader( f );
BufferedReader in = new BufferedReader( is );
or in short form;
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream("data.txt") ) );
String s = in.readLine();
Folder Lab6 Lab6 Examples 03 Copy.java
2016 Winter
19. Write a class named Exercise2 that prints all the lines that
contain a certain word.
For each line containing the word, print the line number
followed by the line itself.
2016 Winter
20. Write a class named Exercise3 that counts the number of
occurrences of a given word within a file.
2016 Winter
21. Write a class Exercise4 that fetches the content of a Web
page and prints it on the console.
2016 Winter
22. There are two useful File utility methods, which can be used to create
directories:
mkdir( ) method creates a directory, returning true on success and false on
failure. Failure indicates that the path specified in the File object already
exists, or that the directory cannot be created because the entire path does
not exist yet.
mkdirs() method creates both a directory and all the parents of the
directory.
import java.io.File;
public class CreateDir {
public static void main(String[] args) {
String dirname = "/tmp/user/java/bin";
File f = new File(dirname);
f.mkdirs(); // Create directory
}
}
2016 Winter
23. Writing to a file involves creating a FileOutputStream object.
We’ll consider two constructors.
FileOutputStream( String name ): Creates an output file
stream to write to the file with the specified name.
OutputStream out = new FileOutputStream( "data.txt" );
FileOutputStream( File file ): This constructor receives a File
object as an argument, which is the representation of an
external file.
File f = new File( "data.txt" );
OutputStream out = new FileOutputStream( f );
2016 Winter
24. Because a FileOutputStream allows to write bytes only, Java defines an
OutputStreamWriter as bridge from byte to character streams. Its usage is
as follows.
OutputStreamWriter out = new OutputStreamWriter (new
FileOutputStream( "data.txt" ));
or
OutputStreamWriter out = new OutputStreamWriter( System.out );
• write( int c ): Writes a single character.
• write( char[] buffer ): Writes an array of characters.
• write( String s ): Writes a String.
2016 Winter
25. Modify the class Copy.java so that it has a second argument
that will be the name of a destination file. An accordingly,
write a copy of the input to the output file.
2016 Winter
26. An exception (or exceptional event) is a problem that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore these exceptions are to be handled.
If a method does not handle a checked exception, the method must declare
it using the throws keyword. The throws keyword appears at the end of a
method's signature.
Catching Exceptions:
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate
an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:
2016 Winter
27. try {
//Protected code
} catch(ExceptionType1 e1) {
//Catch block 1
} catch(ExceptionType2 e2) {
//Catch block 2
}
The code which is prone to exceptions is placed in the try block, when an
exception occurs, that exception occurred is handled by catch block
associated with it. Every try block should be immediately followed either
by a catch block or finally block.
The finally block
The finally block follows a try block or a catch block. A finally block of
code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
2016 Winter
28. public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
2016 Winter
29. IOException
“Signals that an I/O exception of some sort has occurred. This
class is the general class of exceptions produced by failed or
interrupted I/O operations.” This is a direct subclass of
Exception, this is therefore a checked exception that must be
handled, caught by a catch clause or declared.
FileNotFoundException
The constructor FileInputStream( String name ) throws an
exception of type FileNotFoundException, which is a direct
subclass of IOException. This exception must be handled, i.e.
caught by a catch clause or declared.
2016 Winter
30. Again here, the solution proposed by Java is more complex than with most
other programming languages.
java.text.Format
Format is the abstract superclass of all the formatting classes, namely
DateFormat and NumberFormat. The following occurs when printing a
floating point number.
public class Test {
public static void main( String[] args ) {
System.out.println( Math.PI );
}
}
2016 Winter
31. Sometimes this what you want and sometimes not (e.g. printing dollar
amounts). In order to print only a fixed number of decimals, one needs to
create a NumberFormat instance and tell this instance how to format
numbers.
First, the NumberFormat class is not imported by default, therefore you will
have to import it into your program.
Next, you will create and instance and then use the instance methods
setMaximumFractionDigits and setMinimumFractionDigits to set the
number of digits for the fractional part to 2.
Finally, you can use the instance method format, of the number format
object, to create the string representations.
Folder Lab6 Lab6 Examples 04 Test.java
Folder Lab6 Lab6 Examples 04 Test2.java
2016 Winter