SlideShare a Scribd company logo
Input and output streams
C o re j ava volume 2:chapter 2
1
Objectives
• Overview of I/O Streams
• Character Streams
• Byte Streams
• Connected Streams
• Random access files
• Overview of Object serialization
• File system management
• Memory map and file lock
2
Overview of i/o streams
• Input can be from keyboard or a file
• Output can be to display (screen) or a file
• A stream connects a program to an I/O object:
• Input stream: a stream that provides input to a program
• Output stream: a stream that accepts output from a program
• All stream classes that support algorithms for reading and
writing are in java.io package.
3
Standard IO streams
• There are three standard IO streams, all of which are static
members of the java.lang.System class
• Standard input--referenced by System.in (an InputStream)
Used for program input, typically reads input entered by the user (from
keyboard).
• Standard output--referenced by System.out (a PrintStream)
Used for program output, typically displays information to the user (to
screen).
• Standard error--referenced by System.err (a PrintStream)
Used to display error messages to the user (to screen).
4
Files versus Standard IO streams
• Advantages of file I/O
• permanent copy
• output from one program can be input to another
• input can be automated (rather than entered manually)
5
Streams Basics
• Using streams allows the same methods to be used to read or write
data, regardless of its source…we simply create an InputStream or
OutputStream of the appropriate type.
• IO streams are either character-oriented (Formatted- Human ) or
byte-oriented (binary – machine).
• Character-oriented IO is specialized for handling character data. It interprets the
bytes involved in text or record format. The classes are extended from Reader,
Writer
• Byte-oriented IO is general purpose IO that involves all types of data. The classes
are extended from InputStream, OutputStream
• it leaves bytes uninterpreted.
• Application interprets it as it wish (Word, Excel..)
6
Reading & Writing Bytes Stream
• Binary I/O is fast and efficient, BUT it is not easily readable
by humans
• The InputStream class has a method, read(), which reads one byte
from the stream and returns it or -1 at the end of the input stream.
• int available() // returns the number of bytes available.
• int read(byte [] b) // reads into an array of bytes and returns the actual
number of bytes read, or -1 at the end of the input stream
• int read(byte [] b, int off, int len) //reads up to len bytes if available. Values are
placed into b, starting at off. Returns the actual number of bytes read, or -1 at
the end of the input stream
7
Reading & Writing Bytes Stream
• Conversely, the OutputStream class has a method,
write(byte) to write a byte to the stream.
• void flush() // sends any buffered data to its destination.
• void write(byte [] b) // Write the array of byte
• void write(byte [] b, int off, int len) // Write many bytes (len)
starting at off location in the array b
• void close() // flushes and closes the output stream.
8
Reading & Writing Bytes Stream
• Both the read and write methods block until the byte is actually read or written.
• This means that if the input stream cannot immediately be accessed (usually
because of a busy network connection), the current thread blocks. Which gives the
other thread the chance to do useful work while the current thread waiting.
• This means a code that use available() method like the following is unlikely to block:
int bytesAvailable = in.available();
if (bytesAvailable > 0)
{
var data = new byte[bytesAvailable];
in.read(data);
}
9
Reading & Writing Bytes Stream
• The InputStream and OutputStream classes let you read and
write individual bytes and arrays of bytes. Application
programmers rarely use them. The data that you are
interested in probably contain numbers, strings, and objects,
not raw bytes. Less abstracted streamers are required!
• Java provides the DataInputStream/ DataOutputStream classes,
which are capable of directly reading/writing all of the Java
primitive types through method calls such as readDouble(),
readChar(), readBoolean(), writeDouble(), writeChar(), etc…
10
I/O streams attached to Disk File
• FileInputStream inF = new FileInputStream("payroll.dat");
• FileOutputStream outF = new FileOutputStream("payroll.dat");
• Or, using a File object:
• File f = new File("payroll.dat");
• FileInputStream inFile = new FileInputStream(f);
• FileOutputStream outFile = new FileOutputStream(f);
11
I/O streams attached to Disk File
• File class deals with actual storage of the file on disk
• Class File provides three constructors:
• File f=new File(String name)
• File f=new File(String path, String name)
• File f=new File(File dir, String name)
• name specifies the name of a file or directory to associate
with the File object.
• path specifies an absolute or relative path
• File object dir represents a directory
12
I/O streams attached to Disk File
• Name and path must be in host system format anyway using
the suitable separator character:
• forward slashes for Unix: /home/dab/java/data
• backward slashes and drive letters for windows: C:classjavadata
• To obtain the local computer’s proper separator, use
File.separator
File f=new File(“.” + File.separator + “newfile.txt”);
Equivalent to
File f=new File(“./newfile.txt”);
13
I/O streams attached to Disk File
• Absolute path contains all the directories, starting with
the root directory such as:
C:UsersBookDesktopUser
• Relative path starts from the directory in which the
application began executing and is therefore “relative” to
the current directory such as:
File f=new File(".",“test.txt"); // in the current directory
File f=new File(“../",“test.txt"); // in the parent directory
14
File path in windows
• Since the backslash character is the escape character in Java
strings, be sure to use  for Windows style path names
(for example, C:UsersBookDesktopUser)
• In Windows, you can also use a single forward slash
(C:/Users/Book/Desktop/User) because most Windows file
handling System calls will interpret forward slashes as file
separators. However, this is not recommended—the behavior
of the Windows system functions is subject to change
15
Example1: read from a file 16
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException {
FileReader fr = null;
//fr = new FileReader("C:UsersAsusDesktopITcpit305Slides
Hind IOstreamsemployee.txt");
fr = new FileReader("C:/Users/Asus/Desktop/IT/cpit305/Slides Hind/
IOstreams/employee.txt");
int c = 0;
System.out.println("My file separator is: " + File.separator);
while ( fr.ready() )
{
c = fr.read();
System.out.print((char) c); // print the character
}
fr.close() ;
}
}
Example1: read from a file: Output
>>java ReadFile
My file separator is: 
Ahmad 22
Sara 30
Noor 12
17
• In this example we can open the file using the file separator of
windows and Linux, however, the good practice is to use the
right separator for every OS
This is the content
employee.txt
Example1: read from a file without casting 18
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException {
FileReader fr = null;
//fr = new FileReader("C:UsersAsusDesktopITcpit305Slides
HindIOstreamsemployee.txt");
fr = new FileReader("C:/Users/Asus/Desktop/IT/cpit305/Slides
Hind/IOstreams/employee.txt");
int c = 0;
while ( fr.ready() )
{
c = fr.read();
System.out.print(c); // print the code of the character
System.out.print(" "); // print space
}
fr.close() ;
}
}
Example1: read from a file without casting :
Output
>> java ReadFile
65 104 109 97 100 32 50 50 13 10 83 97 114 97 32 51 48 13 10 78 111 111 114 32 49 50 13 10 13
10 13 10
19
• These numbers are the character encoding of each
character in the text file because we did not use casting to
cast the integer c to its equivalent character
Example2: write to a file 20
import java.io.*;
public class WriteFile{
public static void main(String[] args) throws IOException {
FileWriter fw = null;
fw = new FileWriter(".employee.txt");
fw.write("Yara ");
int c=65;
fw.write(c);
fw.close() ;
}
}
Example2: write to a file Output
Content of file before writing:
Ahmad 22
Sara 30
Noor 12
21
Content of file after writing:
Yara A
• If we try to write to a file that doesn’t exist, the file will be
created first, and no exception will be thrown
• We have two problems in this example:
1. write method is overwriting the file.
2. Write(int c) writes the character represented by the integer c
in the default character encoding
Append to file instead of overwrite
• If the FileWriter constructor take just one parameter, the
file name, it will overwrite any existing file
• FileWriter has a constructor that takes 2 parameters too:
The file name and a boolean. The boolean indicates
whether to append or overwrite an existing file
FileWriter fw = new FileWriter(".employee.txt", true); //appends to file
FileWriter fw = new FileWriter(".employee.txt", false); //overwrites file
22
How to write numbers in a text files
• write(int c) expect an encoding number. Solutions:
• We can use write(String) of FileWriter class
1. int c=65;
fw.write(Integer.toString(c));
2. int c=65;
fw.write(c + ”n”); or fw.write(c + ””);
• We can use PrintWriter to wrap the functionality of FileWriter
23
Writing numbers using PrintWriter 24
import java.io.*;
import java.nio.charset.*;
public class WriteFile2{
public static void main(String[] args) throws IOException {
PrintWriter fw = null;
fw = new PrintWriter(new FileWriter(".employee.txt", true));
fw.print("Yara ");
int c=65;
fw.println(c);
fw.close() ;
}
}
This leads us to the concept of connected streams
Writing numbers using PrintWriter: output
Content of file before writing:
Ahmad 22
Sara 30
Noor 12
25
Content of file after writing:
Ahmad 22
Sara 30
Noor 12
Yara 65
• With PrintWriter, it is easier to format the output using the
method printf
• PrintWriter has many constructors:
• one is as the previous example. It allows appending to the file.
• PrintWriter(String fileName), this accept the fine name as string,
but we cannot determine the append option
Character encoding
• Unicode is a character set of various symbols
• Unicode contains code points (numeric value) for almost all represent-able
graphic symbols in the world and it supports all major languages
• https://unicode-table.com/en/#control-character
• UTF-8, UTF-16 and UTF-32 are different ways to represent Unicode code
points in byte format. They differ in the number of bytes needed to
represent the character.
• UTF-8 use 1, 2, 3, or 4 bytes
• UTF-16 use 2 or 4 bytes
• UTF-32 use 4 bytes (fixed width)
26
27
Character encoding
• For example, if the integer 1234 is saved in binary, it is written as
the sequence of bytes 00 00 04 D2 (in hexadecimal notation)
• In text format, it is saved as the string "1234“.
• UTF-8: 31 32 33 34
• Utf-16: 0031 0032 0033 0034
• Although binary I/O is fast and efficient, it is not easily readable by
humans
• When we deal with text files, we need to consider the encoding
scheme to read the right format of the file. Examples 3, 4, and 5
show some methods to determine a specific encoding scheme
28
Example3: read from a text file using a Charset 29
import java.io.*;
import java.nio.charset.*;
public class ReadFileCharset{
public static void main(String[] args) throws IOException {
System.out.println("The default: "+Charset.defaultCharset());
FileReader fr = null;
fr = new
FileReader(".employee.txt",StandardCharsets.UTF_8);//work in
java 11
int c = 0;
while ( fr.ready() )
{
c = fr.read();
System.out.print((char) c); // print the character
}
fr.close() ;
}
}
Example3: read from a text file using a Charset
Output
>>java ReadFileCharset
The default: windows-1252
Ahmad 22
Sara 30
Noor 12
30
>>java ReadFileCharset
The default: UTF-8
Ahmad 22
Sara 30
Noor 12
Result in jdk 17 and earlier versions of java
Result in jdk 18 and newer versions of java
Example4: write in a text file using a Charset 31
import java.io.*;
import java.nio.charset.*;
public class WriteFileCharset{
public static void main(String[] args) throws IOException {
PrintWriter fw = null;
//This constructor works in java 11
fw = new PrintWriter(new
FileWriter(".employee.txt",StandardCharsets.UTF_8, true));
fw.print("Yara ");
int c=65;
fw.println(c);
fw.close() ;
}
}
Example5: read content of file and write it to
another file
32
• Assume that we have the following text file:
• employee16.txt
• This file is encoded using UTF-16 charset
• In Example5 we will read it in different charset to see the
output
Example5: read content of file and write it to
another file
33
import java.io.*;
import java.nio.charset.*;
public class TestCharset{
public static void main(String[] args) throws IOException {
System.out.println("The default: "+Charset.defaultCharset());
FileReader fr = null;
fr = new FileReader(".employee16.txt",StandardCharsets.UTF_8);//work in
java 11
FileWriter fw = null;
//This constructor works in java 11
fw = new FileWriter(".employee3.txt",StandardCharsets.UTF_8, false);
int c = 0;
while ( fr.ready() )
{
c = fr.read();
fw.write(c);
//System.out.print((char) c); // print the character
}
fr.close() ;
fw.close();
}
}
Example5: read content of file and write it to
another file : output
34
• The output will be written in the file: employee3.txt which
looks as following:
• This shows the importance of using the right charset when we
deal with files coming from different platforms
Reading byte-oriented files
• To read or write byte-oriented files use the two classes:
• FileInputStream
• FileOutputStream
• Key differences between a FileReader and a FileInputStream :
1. The first difference is in their type hierarchy, FileReader extends from Reader
class while FileInputStream is descendent of InputStream class.
2. The second difference is in their purpose. The FileReader is meant for reading
text data while FileInputStream is for reading binary data.
3. The various overloaded read() method of FileReader can read one character at a
time or multiple characters into an array while read() method of FileInputStream
can read one byte at a time or multiple bytes in a byte array.
35
Reading byte-oriented files
• Images are type of the byte-oriented files; we cannot deal with
them as text files
• In the following example (Example6) we will read an image, change
some of the bytes, then write the image with different name
 Note: the modification is implemented randomly, i.e. does not
consider the suitable format of jpg files. This example is only
demonstration of the byte-oriented streams
36
Example6: read and write images 37
import java.io.*;
public class TestFileInputStream1
{ public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(".javabig.jpg");
//To get how many bytes in the file
int len = fis.available();
int[] temp = new int[len];
int i = 0; //total number of bytes in the image
while (fis.available() > 0) {
temp[i] = fis.read();
i++;
}
//random modification of the image
for(int j=2000;j<3000;j++)
temp[j]=33;
//write the image in a new file
FileOutputStream fos = new FileOutputStream(".myjavabig.jpg");
for (int j = 0; j < temp.length; j++) {
fos.write(temp[j]);
}
fis.close() ;
fos.close();
System.out.println("n byte[1000] and byte[2000]: "+(char)temp[1000]+
" "+(char)temp[2000] );
System.out.println("n the number of bytes is: "+len);
} }
Example6: read and write images output 38
>>java TestFileInputStream1
byte[1000] and byte[2000]: ? !
the number of bytes is: 66902
Connected streams
• Streams are wrapped to combine the various features of many
streams
• The DataInputStream has no methods to read from a file and the
FileInputStream has no methods to read numeric types
• Java allows you to combine these two types of streams into a
filtered stream or connected streams
• The FileInputStream knows how to read from a file. The
DataInputStream knows how to read an InputStream into useful
types (assemble bytes into more useful data types).
• Connect the out end of the FileInputStream to the in end of the
DataInputStream
39
DataInputStream FileInputStream File
Connected streams
• For example, if we wanted to read numbers from a file, we
create a FileInputStream, to read the bytes from the file, and
then a DataInputStream, which assemble bytes into more
useful data types.
• FileInputStream Fin = new FileInputStream(“java.dat”);
DataInputStream Din = new DataInputStream(Fin);
double num1 = Din.readDouble();
• Data streams do not represent new files but a more capable
interface (i.e., they group bytes into more complex units)
40
DataOutputStream (make binary files)
• The code of the Example7 will store employee records as
binary data
• Assume that the record format is as following
[ID(int) name(String) evaluation(double)]
• The code in Example8 will read the employee records
41
Example7: TestDataOutputStream.java 42
import java.io.*;
public class TestDataOutputStream
{
public static void main(String[] args) throws IOException {
//open the file in overwrite mode (not append)
var dout= new DataOutputStream(new
FileOutputStream(".employeeBinary.txt",false));
/*
employeeBinary.txt has records of employees in the format:
[ID(int) name(String) evaluation(double)]
*/
//first employee
dout.writeInt(1);
dout.writeUTF("Eman"); //write string
dout.writeDouble(23.6);
//second employee
dout.writeInt(2);
dout.writeUTF("Sarah"); //write string
dout.writeDouble(22.5);
dout.close();
}
}
Example7: TestDataOutputStream.java output 43
• Showing the file content in a text editor
Example7: TestDataOutputStream.java output 44
• Showing the file content in a hexadecimal viewer
Example7: TestDataOutputStream.java output 45
• writeInt(int) is writing integer in 4 bytes
• writeDouble(double) is writing double in 8 bytes
• writeUTF(string) writes two bytes of length information to
the output stream, followed by the UTF-8 representation
of every character in the string s
Example8: TestDataInputStream.java 46
import java.io.*;
public class TestDataInputStream
{
public static void main(String[] args) throws IOException {
var din= new DataInputStream(new
FileInputStream(".employeeBinary.txt"));
/*
employeeBinary.txt has records of employees in the format:
[ID(int) name(String) evaluation(double)]
*/
int id; double eval; String str;
while(din.available()>0)
{
id = din.readInt();
str = din.readUTF(); //read string
eval = din.readDouble();
System.out.println("Employee ID#"+id+", name: "+str+", has
evaluation = "+eval);
}
din.close();
}
}
Example8: TestDataInputStream.java output 47
>>java TestDataInputStream
Employee ID#1, name: Eman, has evaluation = 23.6
Employee ID#2, name: Sarah, has evaluation = 22.5
Connected streams: Buffering
• You can add multiple capabilities by nesting the streams
• If you desire buffering on your input streams to speed up data
access, use for example, BufferedInputStream class object.
• Not buffered: each byte is read/written from/to disk as soon as
possible. By default, io streams are unbuffered
• “little” delay for each byte
• A disk operation per byte---higher overhead
48
Connected streams: Buffering
• Buffered: reading/writing in “chunks”
• Some delay for some bytes
• Assume 16-byte buffers:
Reading: access the first 4 bytes, need to wait for all 16 bytes are
read from disk to memory
Writing: save the first 4 bytes, need to wait for all 16 bytes before
writing from memory to disk
• A disk operation per a buffer of bytes---lower overhead
49
Connected streams: Buffering
• Think of this as just another pipe in the chain, that adds
buffering…
DataInputStream din = new DataInputStream(new BufferedInputStream(new
FileInputStream (“employee.dat”)));
50
DataInputStream FileInputStream File
BufferedInputStrea
m
Buffering in java
• There are four buffered stream classes used to wrap
unbuffered streams: BufferedInputStream and
BufferedOutputStream create buffered byte streams, while
BufferedReader and BufferedWriter create buffered
character streams
51
Buffering in java – possible constructors
• Read from myfile.txt in char oriented, buffer size is bufSize
var br= new BufferedReader(new FileReader(“myfile.txt”), bufSize)
• Write (append) into myfile.txt in char oriented, buffer size is bufSize
var bw= new BufferedWriter(new FileWriter(“myfile.txt”,true), bufSize)
• Read from myfile.txt in binary oriented, buffer size is the default: 8 KB
var bi= new BufferedInputStream(new FileInputStream(" myfile.txt"));
• Write (overwrites) into myfile.txt in binary oriented, buffer size bufSize
var bo= new BufferedOutputStream(new FileOutputStream(" myfile.txt"), bufSize);
52
Example 9: using BufferedReader
• In this example we will create object of the class
BufferedReader with the size 10 KB. The default is 8 KB
• It is best to use buffer sizes that are multiples of 1024 bytes.
That works best with most built-in buffering in hard disks etc.
• Except for adding buffering to Reader instances, a Java
BufferedReader behaves pretty much like a Reader. The
BufferedReader has one extra method though, the readLine()
method. This method can be handy if you need to read input
one line at a time
53
Example 9: using BufferedReader 54
import java.io.*;
public class ReadFileBuffered{
public static void main(String[] args) throws IOException {
var fr = new FileReader(".employee.txt");
int bufferSize = 10 * 1024;
var br=new BufferedReader(fr,bufferSize);
String line;
//int c;
while ( br.ready() )
{
/* c = br.read();
System.out.print((char)c); */
line = br.readLine();
System.out.println(line);
}
br.close() ;
}
}
Example 9: using BufferedReader output 55
>>java ReadFileBuffered
Ahmad 22
Sara 30
Noor 12
Flushing buffered streams
• It often makes sense to write out a buffer at critical points,
without waiting for it to fill. This is known as flushing the
buffer
• To flush a stream manually, invoke its flush method. The
flush method is valid on any output stream, but has no
effect unless the stream is buffered
• Flush is called by default when we invoke close() of the
output stream
56
Example 10 and 11: using flush method
• In example 10 we will use Buffered output stream and test
the effect of flush on the output
• In example 11 we will use unbuffered File output stream
and test the effect of flush on the output
57
Example 10: using BufferedOutputStream and
flush
58
import java.io.*;
public class TestBuffer2{
public static void main(String[] args) //throws IOException
{ // using (try-with-resources) we dont need to call close
try( OutputStream os = new FileOutputStream("test.txt");
BufferedOutputStream buffer = new BufferedOutputStream(os);
InputStream is = new FileInputStream("test.txt");
)
{
buffer.write('A');
buffer.write('B');
// read count of what we wrote without flush
System.out.println("count before flush: " + is.available());
buffer.flush();
// read count of what we wrote after flush
System.out.println("count after flush: " + is.available());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
Example 10: using BufferedOutputStream and
flush output
59
>>java TestBuffer2
count before flush: 0
count after flush: 2
Example 11: using OutputStream and flush 60
import java.io.*;
public class TestBuffer3{
public static void main(String[] args) throws IOException
{ // using (try-with-resources) we dont need to call close
try( OutputStream os = new FileOutputStream("test.txt");
InputStream is = new FileInputStream("test.txt");
)
{
os.write('A');
os.write('B');
// read count of what we wrote without flush
System.out.println("count before flush: " + is.available());
os.flush();
// read count of what we wrote after flush
System.out.println("count after flush: " + is.available());
}
}
}
Example 11: using OutputStream and flush
output
61
>>java TestBuffer3
count before flush: 2
count after flush: 2
Random Access files
• The RandomAccessFile class lets you read or write data
anywhere in a file.
• Disk files are random access, but input/output streams
that communicate with a network socket are not
• RandomAccessFile class Open a random-access file either
for reading only or for both reading and writing.
62
Random Access files
• To read:
RandomAccessFile rf = new RandomAccessFile(“employee.txt", "r");
• To read and write:
RandomAccessFile rf = new RandomAccessFile(“employee.txt", "rw");
63
Random Access files
• A randomaccess file has a file pointer that indicates the position of
the next byte to be read or written
• The getFilePointer method and seek method gets/sets the file
pointer to a byte position within the file
• The RandomAccessFile class implements both the DataInput and
DataOutput interfaces. For example, use readInt / writeInt (
readXXX() / writeXXX() where XXX are primitive data types)
• Also it has the method readLine() to read each line of a text file
64
Random Access files
• To determine the number of bytes at a file use length
method
int nbytes = (int) rf.length(); // length in bytes
int nrecords = nbytes / RECORD_SIZE;
• Where RECORD_SIZE is the size of each record in the file
65
Random Access files
• To position the file pointer to the third record:
int i = 3;
rf.seek((i – 1) * RECORD_SIZE);
• Then we can read or write at that position
• The RandomAccessFile is more useful when we have
records of fixed length
66
Random Access files – try with resources
• We can open the files in a block called try-with-resources
• It is an alternative for try-catch-finally blocks
• It will close the file automatically without close method
and optionally you can add catch or finally blocks
67
Example12: TestRandomAccess1 page 1 68
import java.io.*;
import java.util.*;
import java.nio.charset.*;
public class TestRandomAccess1{
public static void main(String[] args) throws IOException {
var staff = new Employee[3];
staff[0] = new Employee(1,"Sara", 7500);
staff[1] = new Employee(2,"Noor", 5000);
staff[2] = new Employee(3,"Amal", 4000);
String temp;
// Writing employee records into employee.txt as records of fixed
length
try (var out = new
FileWriter(".//employee.txt",StandardCharsets.UTF_8))
{
for (Employee e : staff)
{
temp=Integer.toString(e.getID());
out.write(fixedString(temp,Employee.ID_SIZE));
out.write(fixedString(e.getName(),Employee.NAME_SIZE));
temp=Double.toString(e.getSalary());
out.write(fixedString(temp,Employee.SALARY_SIZE));
out.write("n"); //test 'n'
}
}
Example12: TestRandomAccess1 page 2 69
try (var rf = new RandomAccessFile("employee.txt", "rw"))
{
// retrieve all records into a new array
// compute the array size
System.out.println("file length= "+rf.length()+" Bytes");
int n = (int)(rf.length() / Employee.RECORD_SIZE);
var newStaff = new Employee[n];
System.out.println("number of employees= "+n);
System.out.println("Record size="+ Employee.RECORD_SIZE);
// read employees in reverse order
for (int i = n - 1; i >= 0; i--)
{
rf.seek(i * Employee.RECORD_SIZE);
String str = rf.readLine();
StringTokenizer tokens = new StringTokenizer(str);
int tokenID= Integer.parseInt(tokens.nextToken());
String tokenName=tokens.nextToken();
double tokenSalary= Double.parseDouble(tokens.nextToken());
newStaff[i] = new Employee(tokenID,tokenName,tokenSalary);
}
// print the newly read employee records
System.out.println("Emplyees reading by RandomAccess class: ");
for (Employee e : newStaff)
System.out.println(e);
Example12: TestRandomAccess1 page 3 70
// change the second record
int r=2;
rf.seek((r - 1) * Employee.RECORD_SIZE);
String str = rf.readLine();
String[] tokens = str.split("s+");
int tokenID= Integer.parseInt(tokens[0]);
String tokenName=tokens[1];
double tokenSalary= Double.parseDouble(tokens[2]);
tokenSalary*=2;
System.out.println("We doubled the salary of this employee: "+str);
rf.seek(((r - 1) * Employee.RECORD_SIZE) + (Employee.ID_SIZE +
Employee.NAME_SIZE) );
temp=Double.toString(tokenSalary);
rf.writeBytes(fixedString(temp,Employee.SALARY_SIZE));
}
}
Example12: TestRandomAccess1 page 4 71
public static String fixedString(String s, int size)
{
char[] array=new char[size];
for (int i = 0; i < size; i++)
{
if (i < s.length())
array[i] = s.charAt(i);
else
array[i]=' ';
}
return new String(array);
}
}
Example12: TestRandomAccess1 page 5 72
//-------Employee class--
class Employee
{ //following constants used only to save records in the text file
public static final int NAME_SIZE = 10;
public static final int ID_SIZE = 4;
public static final int SALARY_SIZE = 10;
public static final int RECORD_SIZE = (NAME_SIZE + ID_SIZE +
SALARY_SIZE) + 1; //last 1 is for n
private int id;
private String name;
private double salary;
public Employee() {}
public Employee(int i, String n, double s)
{
id=i;
name = n;
salary = s;
}
public String getName()
{
return name;
}
Example12: TestRandomAccess1 page 6 73
public double getSalary()
{
return salary;
}
public int getID()
{
return id;
}
public String toString()
{
return "Employee" //"Employee"
+ "[name=" + name
+ ",salary=" + salary
+ ",ID=" + id
+ "]";
}
}
Example12: TestRandomAccess1 output 74
>>java TestRandomAccess1
file length= 75 Bytes
number of employees= 3
Record size=25
Emplyees reading by RandomAccess class:
Employee[name=Sara,salary=7500.0,ID=1]
Employee[name=Noor,salary=5000.0,ID=2]
Employee[name=Amal,salary=4000.0,ID=3]
We doubled the salary of this employee: 2 Noor 5000.0
Example12: TestRandomAccess1 output 75
Scanner class
• It is a simple text scanner which can parse primitive types
and strings using regular expressions
• A Scanner breaks its input into tokens using a delimiter
pattern, which by default matches whitespace
• The resulting tokens may then be converted into values of
different types using the various next methods
76
Scanner class
• It has many constructors, such as:
• Scanner(File source) produces values scanned from a file
• Scanner(InputStream source) produces values scanned from
input stream such as System.in
• Scanner(String source) produces values scanned from string
77
Scanner class
• We can change the default delimiter using the method:
useDelimiter
• To set single delimiter, we use simple string that include the
delimiter
• sc.useDelimiter(“,”) will split the string based on the occurrence of ,
• sc.useDelimiter(“//”) will split the string based on the occurrence of //
• To set multiple delimiters, we should use regex:
78
Scanner class - regex
• Regex is a regular expression defines a search pattern for
strings
• The search pattern can be anything from a simple
character, a fixed string or a complex expression
containing special characters
79
Scanner class - regex
• To use multiple characters in regex we use |
• Example, sc.useDelimiter(“, | .”) will make the delimiter
as , or .
• The dot symbol (.) has special meaning for regex (it
matches any single character) so we need to escape it with
 to be used literally. In addition,  is escape character in
java strings so we need to escape it by another 
80
Example14: TestScannerTokens 81
import java.io.*;
import java.util.*;
public class TestScannerTokens{
public static void main(String[] args) throws IOException {
Scanner sc1 = new Scanner("that, that is, is");
while(sc1.hasNext())
System.out.println("Tokens of sc1: <" + sc1.next() + ">");
System.out.println(" -------- ");
Scanner sc2 = new Scanner("that, that is, is");
sc2.useDelimiter(",");
while(sc2.hasNext())
System.out.println("Tokens of sc2: <" + sc2.next() + ">");
System.out.println(" -------- ");
Scanner sc3 = new Scanner("http://192.173.15.36:8084/abc");
sc3.useDelimiter(":|/|."); //sc3.useDelimiter("://|/|:|.");
while(sc3.hasNext())
System.out.println("Tokens of sc3: <" + sc3.next() + ">");
System.out.println(" -------- ");
Scanner sc4 = new Scanner("abcdef");
sc4.useDelimiter(""); //just to make  as delimiter
while(sc4.hasNext())
System.out.println("Tokens of sc4: <" + sc4.next() + ">");
}}
Example14: TestScannerTokens output 82
>>java TestScannerTokens
Tokens of sc1: <that,>
Tokens of sc1: <that>
Tokens of sc1: <is,>
Tokens of sc1: <is>
--------
Tokens of sc2: <that>
Tokens of sc2: < that is>
Tokens of sc2: < is>
--------
Tokens of sc3: <http>
Tokens of sc3: <>
Tokens of sc3: <>
Tokens of sc3: <192>
Tokens of sc3: <173>
Tokens of sc3: <15>
Tokens of sc3: <36>
Tokens of sc3: <8084>
Tokens of sc3: <abc>
--------
Tokens of sc4: <abc>
Tokens of sc4: <def>
Example12: TestScannerTokens output
• Why we need four backslashes to have  delimiter?
• The reason behind this is that your string is de-escaped
twice. Once at compile time as every other string literal in
the Java language, and once at the parsing by the regex
class. That means, after the first step it is escaped once,
so the regex parser gets two backslashes . The regex
parser will de-escape that too, and will match a single 
character
83
String.split method
• The split method in String class is working using regex, i.e.
exactly like Scanner tokenization
• In the following slide we will repeat the Scanner example
but with split method, and we will use exactly the same
regular expressions
84
Example15: TestSplitTokens 85
import java.io.*;
import java.util.*;
public class TestSplitTokens{
public static void main(String[] args) throws IOException {
int i;
String st1="that, that is, is";
String[] tokens1=st1.split("s");
i=0;
while(i<tokens1.length)
System.out.println("Tokens of st1: <"+tokens1[i++] + ">");
System.out.println(" -------- ");
String st2="that, that is, is";
String[] tokens2=st2.split(",");
i=0;
while(i<tokens2.length)
System.out.println("Tokens of st2: <"+tokens2[i++] + ">");
System.out.println(" -------- ");
String st3="http://192.173.15.36:8084/abc";
String[] tokens3=st3.split(":|/|.");
i=0;
while(i<tokens3.length)
System.out.println("Tokens of st3: <"+tokens3[i++] + ">");
System.out.println(" -------- ");
String st4="abcdef";
String[] tokens4=st4.split("");
i=0;
while(i<tokens4.length)
System.out.println("Tokens of st4: <"+tokens4[i++] + ">");
}}
Example15: TestSplitTokens output 86
>>java TestSplitTokens
Tokens of st1: <that,>
Tokens of st1: <that>
Tokens of st1: <is,>
Tokens of st1: <is>
--------
Tokens of st2: <that>
Tokens of st2: < that is>
Tokens of st2: < is>
--------
Tokens of st3: <http>
Tokens of st3: <>
Tokens of st3: <>
Tokens of st3: <192>
Tokens of st3: <173>
Tokens of st3: <15>
Tokens of st3: <36>
Tokens of st3: <8084>
Tokens of st3: <abc>
--------
Tokens of st4: <abc>
Tokens of st4: <def>
Object serialization
• Serialization is a mechanism of converting the state of an object
into a byte stream. Deserialization is the reverse process where
the byte stream is used to recreate the actual Java object in
memory
• The byte stream created is platform independent. So, the
object serialized on one platform can be sent on network or
saved to database and deserialized on a different platform
• To make a Java object serializable, its class should implement
the java.io.Serializable interface
87
Object serialization
• The Serializable interface has no methods, so you don’t
need to change your classes in any way
• ObjectOutputStream class is used to write objects in the
serialization process using the method writeObject
• ObjectInputStream class is used to read objects in the
deserialization process using the method readObject
• When you use readObject method, you should explicitly
cast the loaded object
88
Serialization
• It is possible to write or read array of objects at one call for
the writeObject and readObject methods
• Behind the scenes, an ObjectOutputStream looks at all
the fields of the objects and saves their contents based on
their type
• Note: static fields belong to a class (as opposed to an
object) and are not serialized
89
Example16: TestSerialize 90
import java.io.*;
public class TestSerialize{
public static void main(String[] args) throws IOException,
ClassNotFoundException
{
var sara = new Employee("Sara", 5000);
var nora = new Employee("Nora", 8000);
var amal = new Employee("Amal", 9000);
var staff = new Employee[3];
staff[0] = sara;
staff[1] = nora;
staff[2] = amal;
try (var out = new ObjectOutputStream(new
FileOutputStream("employee.dat")))
{
out.writeObject(staff);
}
// retrieve all records into a new array
try (var in = new ObjectInputStream(new
FileInputStream("employee.dat")))
{
var newStaff = (Employee[]) in.readObject();
for (Employee e : newStaff)
System.out.println(e);
}
}}
Example16: TestSerialize 91
class Employee implements Serializable
{
private String name;
private double salary;
public Employee() {}
public Employee( String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public String toString()
{
return "Employee"
+ "[name=" + name
+ ",salary=" + salary
+ "]";
Example16: TestSerialize output 92
>>java TestSerialize
Employee[name=Sara, salary=5000.0]
Employee[name=Nora, salary=8000.0]
Employee[name=Amal, salary=9000.0]
Java.nio.file package - file system management
• The java.io.File class was the old mechanism used for file I/O,
but it had several drawbacks:
• Many methods didn't throw exceptions when they failed, so it was
impossible to obtain a useful error message.
• The rename method didn't work consistently across platforms
• There was no real support for symbolic links (in Linux)
• More support for metadata was desired, such as file permissions, file
owner, and other security attributes
• Many of the File methods didn't scale. Requesting a large directory
listing over a server could result in a hang.
• The good alternative of java.io.File is java.nio.file.Path
93
Java.nio.file package – Path and Paths
• To work with Files, we need the following terms:
Path: This is the interface that replaces java.io.File class as the
representation of a file or a directory when we work in Java NIO.
Paths: This class contains a static methods to create Path instance.
• java.nio.file.Path interface is just like the old java.io.File
class. Path represents location of the file.
94
Java.nio.file package – file system management
• Java Files class contains static methods that work on files
and directories
• This class is used for basic file operations like create, read,
write, copy and delete the files or directories of the file
system. These methods mostly works on Path instance
95
How to Create Path
• We can create an object of Path by calling Paths.get(String
first, String... more) method of Paths class such as:
Path path1 = Paths.get("D:/data/file.txt");
• When we create a Path to new file, it does not create
actual file until we create it using Files.createFile(Path
filePath)
96
Create new directory
• To create a new directory, call:
Files.createDirectory(path)
• All but the last component in the path must already exist. If
directory is already existing, then it will throw
nio.file.FileAlreadyExistsException
• To create intermediate directories as well, use:
Files.createDirectories(path);
Creates a directory by creating all nonexistent parent directories first.
• These two methods will return the path of the created
directory
97
Create empty file
• You can create an empty file with:
• Files.createFile(path);
• The call throws an exception if the file already exists
• It will return the path of the created file
98
Copying, moving, and deleting Files
• To copy a file from one location to another, simply call:
Files.copy(fromPath, toPath);
• To move the file (that is, copy and delete the original), call:
Files.move(fromPath, toPath);
• The copy or move will fail if the target (toPath) exists with
the checked exception FileAlreadyExistsException
99
Copying, moving, and deleting Files
• If you want to overwrite an existing target, use the
REPLACE_EXISTING option. You can supply both like this:
Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING);
• StandardCopyOption is enum that contains some
constants to determine the options of file copying and
moving
100
Copying, moving, and deleting Files
• Finally, to delete a file, simply call
Files.delete(path);
• This method throws an exception if the file doesn’t exist, so
instead you may want to use:
boolean deleted = Files.deleteIfExists(path);
• The deletion methods can also be used to remove an
empty directory
101
Using Files.writeString
• The method writeString is a static method in Files class with the
following signature:
public static Path writeString(Path path, CharSequence csq,
OpenOption... options) throws IOException
• CharSequence is an interface that is implemented by String class
• OpenOption is an interface that is implemented by the enum
StandardOpenOption
• Some of the options in StandardOpenOption are:
• APPEND: Append to the existing file
• CREATE: Create a new file if it does not exist.
102
Getting file information
• The following static methods return a Boolean value to
check a property of a path
• exists
• isHidden
• isReadable, isWritable, isExecutable
• isRegularFile, isDirectory
• The size method returns the number of bytes in a file.
long fileSize = Files.size(path);
103
Visiting Directory Entries
• The static Files.list method returns a Stream<Path> that reads
the entries of a directory
• Since reading a directory involves a system resource that
needs to be closed, you should use a try block
• try (Stream<Path> entries = Files.list(pathToDirectory))
• The list method does not enter subdirectories. To process all
descendants of a directory, use the Files.walk method instead.
• try (Stream<Path> entries = Files.walk(pathToDirectory))
104
Example 17: TestFiles.java page 1 105
import java.io.*;
import java.nio.file.*;
import java.util.stream.Stream;
public class TestFiles{
public static void main(String[] args) throws IOException {
// initialize Path object of a directory
Path pathDirectory=Paths.get(".MyDirectory");
//creat the directory
Path createdDir = Files.createDirectory(pathDirectory);
System.out.println("The created directory: "+createdDir);
// initialize Path object of a txt file
Path path1=Paths.get(".MyDirectorymyfile1.txt");
//creat the file
Path createdFile1 = Files.createFile(path1);
System.out.println("The first created file: "+createdFile1);
//writing to the created file (myfile1.txt)
Files.writeString(path1,"some test content in myfile1.txt"); //write will
close the file itself
Example 17: TestFiles.java page 2 106
//intialize another Path object
Path path2=Paths.get(".MyDirectorymyfile2.txt");
Path createdFile2 = Files.writeString(path2,"some test content in
myfile2.txt",StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("The second created file: "+createdFile2);
//copying myfile2.txt to the parent directory and name it myfile3.txt
Path target = Paths.get(".myfile3.txt");
Files.copy(path2, target);
System.out.println("Target file Path : "+target);
System.out.println("Content of target: n"+new
String(Files.readAllBytes(target)));
Example 17: TestFiles.java page 3 107
//listing content of current directory
Path current = Paths.get(".");
try (Stream<Path> mylist = Files.walk(current)) {
System.out.println("n Following are the files end with
.java n");
mylist.forEach( p -> {
String s = p.toString();
if (s.matches(".*.java"))
System.out.println(s);
}
);
}//end of try-with-resources
try (Stream<Path> mylist = Files.walk(current)) {
System.out.println("n Following are all the content of
current directory n");
mylist.forEach( p ->System.out.println(p));
}//end of try-with-resources
}
}
Example 17: TestFiles.java output 108
C:UsersAsusDesktopITCPIT305Slides HindIOstreams>java TestFiles
The created directory: .MyDirectory
The first created file: .MyDirectorymyfile1.txt
The second created file: .MyDirectorymyfile2.txt
Target file Path : .myfile3.txt
Content of target:
some test content in myfile2.txt
Following are the files end with .java
.ExampleError.java
.ReadFile.java
.ReadFileBuffered.java
.ReadFileCharset.java
.TestArabic.java
.TestBuffer1.java
.TestBuffer2.java
.TestBuffer3.java
.TestCharset.java
.TestDataInputStream.java
.TestDataOutputStream.java
.TestFileInputStream.java
……..
Example 17: TestFiles.java output 109
Following are all the content of current directory
.
.iodata.txt
.IOStream.pptx
.javabig.jpg
.MyDirectory
.MyDirectorymyfile1.txt
.MyDirectorymyfile2.txt
.myfile3.txt
.myjavabig.jpg
.myjavabigSector.jpg
.ReadFile.class
.ReadFile.java
.ReadFileBuffered.class
.ReadFileBuffered.java
.ReadFileCharset.class
……
Streams
• Interface Stream<T>
• A stream is not a data structure instead it takes input from
other java objects
• Hence, it is a sequence of elements supporting various
methods such as forEach
• forEach: used to iterate through every element of the stream
• It has one argument with the type: Consumer interface
• Consumer is a functional interface with one abstract method
(void accept​(T t)), so can be used for lambda expression
110
Lambda expression
• Lambda expressions basically express instances of functional
interfaces (An interface with single abstract method).
• lambda expressions implement the only abstract function and
therefore implement functional interfaces
• It provides the following functionalities:
• Enable to treat functionality as a method argument
• A function that can be created without belonging to any class
111
Lambda expression
• The simplest lambda expression contains a single parameter and an
expression:
• parameter -> expression
• To use more than one parameter, wrap them in parentheses:
• (parameter1, parameter2) -> expression
• Expressions are limited. They cannot contain variables, assignments
or statements such as if or for. In order to do more complex
operations, a code block can be used with curly braces. If the
lambda expression needs to return a value, then the code block
should have a return statement.
• (parameter1, parameter2) -> { code block }
112
Lambda expression
• If a lambda expression has no parameters, you still supply
empty parentheses:
• () -> { code block }
• If the parameter types of a lambda expression can be inferred,
you can omit them
• Any lambda expression can be replaced with an object of
anonymous class that implement the functional interface
• Also, any lambda expression can be replaced with an object
of inner class that implement the functional interface
113
Example 18: printing content of directory using
anonymous class instead of Lambda expression
114
import java.io.*;
import java.nio.file.*;
import java.util.function.*;
import java.util.stream.Stream;
public class TestFiles1{
public static void main(String[] args) throws IOException {
//listing content of current directory
Path current = Paths.get(".");
try (Stream<Path> mylist = Files.walk(current)) {
System.out.println("n Following are all the content of current
directory n");
mylist.forEach( new Consumer<Path>() {
public void accept(Path p){
System.out.println(p);
}//end of accept method
});//end of forEach call
}//end of try-with-resources
}
}
Example 18: TestFiles1.java output 115
C:UsersAsusDesktopITCPIT305Slides HindIOstreams>java TestFiles1
Following are all the content of current directory
.
.iodata.txt
.IOStream.pptx
.javabig.jpg
.MyDirectory
.MyDirectorymyfile1.txt
.MyDirectorymyfile2.txt
.myfile3.txt
.myjavabig.jpg
.myjavabigSector.jpg
.ReadFile.class
.ReadFile.java
.ReadFileBuffered.class
.ReadFileBuffered.java
.ReadFileCharset.class
……
Example 19: repeat Ex18 using inner class
116
public class TestFiles2{
public static void main(String[] args) throws IOException {
var obj = new TestInner();
obj.printDirectories();
} }
class TestInner {
public TestInner() {}
public void printDirectories() throws IOException
{
//listing content of current directory
Path current = Paths.get(".");
try (Stream<Path> mylist = Files.walk(current)) {
System.out.println("n Following are all the content of current
directory n");
var myConsumer = new myInner();
mylist.forEach(myConsumer);
}//end of try-with-resources
}
private class myInner implements Consumer<Path>
{
public myInner()
{}
public void accept(Path p){
System.out.println(p);
}//end of accept method
}// end of inner class
}
Example 19: TestFiles2.java output 117
C:UsersAsusDesktopITCPIT305Slides HindIOstreams>java TestFiles2
Following are all the content of current directory
.
.iodata.txt
.IOStream.pptx
.javabig.jpg
.MyDirectory
.MyDirectorymyfile1.txt
.MyDirectorymyfile2.txt
.myfile3.txt
.myjavabig.jpg
.myjavabigSector.jpg
.ReadFile.class
.ReadFile.java
.ReadFileBuffered.class
.ReadFileBuffered.java
.ReadFileCharset.class
……
Class files created by compiler in the previous two examples
118
File locking
• When multiple simultaneously executing programs need
to modify the same file, they need to control its access in
some way, or the file can easily become damaged.
• File locks can solve this problem. A file lock controls access
to a file or a range of bytes within a file
119
File locking – a possible scenario
• Suppose your application saves a configuration file with user
preferences. If a user invokes two instances of the application.
• It could happen that both of them want to write the
configuration file at the same time.
• In that situation, the first instance should lock the file.
• When the second instance finds the file locked, it can decide
to wait until the file is unlocked or simply skip the writing
process
120
File locking
• java programming language supports file locking with the
java.nio package
• First step to lock file is to get a channel for the required file
• A channel is an abstraction for a disk file that lets you
access operating system features such as memory
mapping and file locking
121
File locking
Path path1 = Paths.get(“./file.txt");
FileChannel channel1 = FileChannel.open(path1,
StandardOpenOption.READ);
• By default, the channel is opened for reading, so, the
second argument is optional. The parameter options can
be READ, WRITE, or APPEND in the StandardOpenOption
enumeration.
122
File locking
• Second step to lock a file, call either the lock or tryLock
methods of the FileChannel class
Path path1 = Paths.get(“./file.txt");
FileChannel channel1 = FileChannel.open(path1,
StandardOpenOption.WRITE);
FileLock lock1 = channel1.lock();
Or
FileLock lock2 = channel1.tryLock();
123
File locking
• The first method [lock()] blocks until the lock becomes
available. The second method [tryLock()] returns
immediately, either with the lock or with null if the lock is
not available.
• The file remains locked until the channel is closed:
channel1.close();
• or the release method is invoked on the lock:
lock1.release();
124
File locking
• To have a shared lock on only part of the file, we can use the
following syntax of lock method
FileLock lock1 = channel1.lock(long start, long size, boolean shared)
• Or
FileLock lock1 = channel1.tryLock(long start, long size, boolean shared)
• The parameter shared is true for a shared lock, false for an
exclusive lock. The shared lock allows multiple processes to
read from the file, while preventing any process from acquiring
an exclusive lock
125
File locking – Exclusive lock
• To get an exclusive lock, we must use a writable
FileChannel. For example:
try ( FileChannel channel = FileChannel.open(path,
StandardOpenOption.APPEND);
FileLock lock = channel.lock() ) {
// write to channel
}
• If you try to acquire an exclusive lock of read-only channel, the
lock() method will throw an Exception
126
File locking – shared lock
• Shared locks are also called read locks. Hence, to get a read
lock, we must use a readable FileChannel. For example:
try (FileChannel channel = FileChannel.open(path,
StandardOpenOption.READ);
FileLock lock = channel.lock(0, channel.size(), true)) {
// read from the channel
}
• If you try to acquire a shared lock of writable channel, the
lock() method will throw an Exception
127
File locking
• Be sure to unlock the lock when you are done.
• The unlock is best done with a try-with-resources
statement:
try (FileLock lock1 = channel1.lock())
{
access the locked file
}
• Try-with-resources will release the lock when its block end
128
To summarize
Input Output
DataInputStream(InputStream in) DataOutputStream(OutputStream out)
1- FileInputStream(String name)
2- FileInputStream(File file)
1- FileOutputStream(String name)
2- FileOutputStream(String name, boolean
append)
3- FileOutputStream(File file)
4- FileOutputStream(File file, boolean
append)
1- FileReader(String fileName)
2- FileReader(File file)
1- FileWriter(String fileName)
2- FileWriter(String fileName, boolean
append)
3- FileWriter(File file)
4- FileWriter(File file, boolean append)
129
To summarize
Input Output
1- BufferedInputStream(InputStream
in)
2- BufferedInputStream(InputStream in,
int size)
1- BufferedOutputStream(OutputStream out)
2- BufferedOutputStream(OutputStream out,
int size)
1- BufferedReader(FileReader in)
2- BufferedReader(FileReader in, int
size)
1- BufferedWriter(FileWriter out)
2- BufferedWriter (FileWriter out, int size)
ObjectInputStream(InputStream in) ObjectOutputStream(OutputStream out)
1- RandomAccessFile(String file, String mode)
2- RandomAccessFile(File file, String mode)
130

More Related Content

PPTX
Input output files in java
PDF
Java Day-6
PPTX
Java I/O
PDF
PDF
CSE3146-ADV JAVA M2.pdf
PPTX
L21 io streams
PPTX
File Input and output.pptx
PPTX
Java Tutorial Lab 6
Input output files in java
Java Day-6
Java I/O
CSE3146-ADV JAVA M2.pdf
L21 io streams
File Input and output.pptx
Java Tutorial Lab 6

Similar to IOStream.pptx (20)

PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PPTX
IO Programming.pptx all informatiyon ppt
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
PPTX
PPT
Javaio
PPT
Javaio
PPT
ch09.ppt
PDF
Java IO
PDF
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
PDF
Basic i/o & file handling in java
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
PPS
Files & IO in Java
PPTX
Chapter 6
PPTX
Java Input Output (java.io.*)
PDF
Programming language JAVA Input output opearations
PDF
File Handling in Java.pdf
PDF
Java IO Stream, the introduction to Streams
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
IO Programming.pptx all informatiyon ppt
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Javaio
Javaio
ch09.ppt
Java IO
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
Basic i/o & file handling in java
Itp 120 Chapt 19 2009 Binary Input & Output
chapter 2(IO and stream)/chapter 2, IO and stream
Files & IO in Java
Chapter 6
Java Input Output (java.io.*)
Programming language JAVA Input output opearations
File Handling in Java.pdf
Java IO Stream, the introduction to Streams
Ad

Recently uploaded (20)

PDF
Instagram's Product Secrets Unveiled with this PPT
PPTX
Understanding-Communication-Berlos-S-M-C-R-Model.pptx
PDF
Swiggy’s Playbook: UX, Logistics & Monetization
PPTX
worship songs, in any order, compilation
PPTX
The Effect of Human Resource Management Practice on Organizational Performanc...
PPTX
Self management and self evaluation presentation
PDF
Nykaa-Strategy-Case-Fixing-Retention-UX-and-D2C-Engagement (1).pdf
PPTX
Relationship Management Presentation In Banking.pptx
PPTX
Non-Verbal-Communication .mh.pdf_110245_compressed.pptx
PPTX
Biography Text about someone important in life
PPTX
Learning-Plan-5-Policies-and-Practices.pptx
PPTX
Primary and secondary sources, and history
PDF
oil_refinery_presentation_v1 sllfmfls.pdf
PPTX
What is Clause, definition and structure
DOC
学位双硕士UTAS毕业证,墨尔本理工学院毕业证留学硕士毕业证
PPTX
Phrase, structure, use, definition in sentence
PPTX
Caption Text about Social Media Post in Internet
PPTX
Presentation for DGJV QMS (PQP)_12.03.2025.pptx
PPTX
Emphasizing It's Not The End 08 06 2025.pptx
PPTX
Called To More (Final I Think) 08 03 2025.pptx
Instagram's Product Secrets Unveiled with this PPT
Understanding-Communication-Berlos-S-M-C-R-Model.pptx
Swiggy’s Playbook: UX, Logistics & Monetization
worship songs, in any order, compilation
The Effect of Human Resource Management Practice on Organizational Performanc...
Self management and self evaluation presentation
Nykaa-Strategy-Case-Fixing-Retention-UX-and-D2C-Engagement (1).pdf
Relationship Management Presentation In Banking.pptx
Non-Verbal-Communication .mh.pdf_110245_compressed.pptx
Biography Text about someone important in life
Learning-Plan-5-Policies-and-Practices.pptx
Primary and secondary sources, and history
oil_refinery_presentation_v1 sllfmfls.pdf
What is Clause, definition and structure
学位双硕士UTAS毕业证,墨尔本理工学院毕业证留学硕士毕业证
Phrase, structure, use, definition in sentence
Caption Text about Social Media Post in Internet
Presentation for DGJV QMS (PQP)_12.03.2025.pptx
Emphasizing It's Not The End 08 06 2025.pptx
Called To More (Final I Think) 08 03 2025.pptx
Ad

IOStream.pptx

  • 1. Input and output streams C o re j ava volume 2:chapter 2 1
  • 2. Objectives • Overview of I/O Streams • Character Streams • Byte Streams • Connected Streams • Random access files • Overview of Object serialization • File system management • Memory map and file lock 2
  • 3. Overview of i/o streams • Input can be from keyboard or a file • Output can be to display (screen) or a file • A stream connects a program to an I/O object: • Input stream: a stream that provides input to a program • Output stream: a stream that accepts output from a program • All stream classes that support algorithms for reading and writing are in java.io package. 3
  • 4. Standard IO streams • There are three standard IO streams, all of which are static members of the java.lang.System class • Standard input--referenced by System.in (an InputStream) Used for program input, typically reads input entered by the user (from keyboard). • Standard output--referenced by System.out (a PrintStream) Used for program output, typically displays information to the user (to screen). • Standard error--referenced by System.err (a PrintStream) Used to display error messages to the user (to screen). 4
  • 5. Files versus Standard IO streams • Advantages of file I/O • permanent copy • output from one program can be input to another • input can be automated (rather than entered manually) 5
  • 6. Streams Basics • Using streams allows the same methods to be used to read or write data, regardless of its source…we simply create an InputStream or OutputStream of the appropriate type. • IO streams are either character-oriented (Formatted- Human ) or byte-oriented (binary – machine). • Character-oriented IO is specialized for handling character data. It interprets the bytes involved in text or record format. The classes are extended from Reader, Writer • Byte-oriented IO is general purpose IO that involves all types of data. The classes are extended from InputStream, OutputStream • it leaves bytes uninterpreted. • Application interprets it as it wish (Word, Excel..) 6
  • 7. Reading & Writing Bytes Stream • Binary I/O is fast and efficient, BUT it is not easily readable by humans • The InputStream class has a method, read(), which reads one byte from the stream and returns it or -1 at the end of the input stream. • int available() // returns the number of bytes available. • int read(byte [] b) // reads into an array of bytes and returns the actual number of bytes read, or -1 at the end of the input stream • int read(byte [] b, int off, int len) //reads up to len bytes if available. Values are placed into b, starting at off. Returns the actual number of bytes read, or -1 at the end of the input stream 7
  • 8. Reading & Writing Bytes Stream • Conversely, the OutputStream class has a method, write(byte) to write a byte to the stream. • void flush() // sends any buffered data to its destination. • void write(byte [] b) // Write the array of byte • void write(byte [] b, int off, int len) // Write many bytes (len) starting at off location in the array b • void close() // flushes and closes the output stream. 8
  • 9. Reading & Writing Bytes Stream • Both the read and write methods block until the byte is actually read or written. • This means that if the input stream cannot immediately be accessed (usually because of a busy network connection), the current thread blocks. Which gives the other thread the chance to do useful work while the current thread waiting. • This means a code that use available() method like the following is unlikely to block: int bytesAvailable = in.available(); if (bytesAvailable > 0) { var data = new byte[bytesAvailable]; in.read(data); } 9
  • 10. Reading & Writing Bytes Stream • The InputStream and OutputStream classes let you read and write individual bytes and arrays of bytes. Application programmers rarely use them. The data that you are interested in probably contain numbers, strings, and objects, not raw bytes. Less abstracted streamers are required! • Java provides the DataInputStream/ DataOutputStream classes, which are capable of directly reading/writing all of the Java primitive types through method calls such as readDouble(), readChar(), readBoolean(), writeDouble(), writeChar(), etc… 10
  • 11. I/O streams attached to Disk File • FileInputStream inF = new FileInputStream("payroll.dat"); • FileOutputStream outF = new FileOutputStream("payroll.dat"); • Or, using a File object: • File f = new File("payroll.dat"); • FileInputStream inFile = new FileInputStream(f); • FileOutputStream outFile = new FileOutputStream(f); 11
  • 12. I/O streams attached to Disk File • File class deals with actual storage of the file on disk • Class File provides three constructors: • File f=new File(String name) • File f=new File(String path, String name) • File f=new File(File dir, String name) • name specifies the name of a file or directory to associate with the File object. • path specifies an absolute or relative path • File object dir represents a directory 12
  • 13. I/O streams attached to Disk File • Name and path must be in host system format anyway using the suitable separator character: • forward slashes for Unix: /home/dab/java/data • backward slashes and drive letters for windows: C:classjavadata • To obtain the local computer’s proper separator, use File.separator File f=new File(“.” + File.separator + “newfile.txt”); Equivalent to File f=new File(“./newfile.txt”); 13
  • 14. I/O streams attached to Disk File • Absolute path contains all the directories, starting with the root directory such as: C:UsersBookDesktopUser • Relative path starts from the directory in which the application began executing and is therefore “relative” to the current directory such as: File f=new File(".",“test.txt"); // in the current directory File f=new File(“../",“test.txt"); // in the parent directory 14
  • 15. File path in windows • Since the backslash character is the escape character in Java strings, be sure to use for Windows style path names (for example, C:UsersBookDesktopUser) • In Windows, you can also use a single forward slash (C:/Users/Book/Desktop/User) because most Windows file handling System calls will interpret forward slashes as file separators. However, this is not recommended—the behavior of the Windows system functions is subject to change 15
  • 16. Example1: read from a file 16 import java.io.*; public class ReadFile{ public static void main(String[] args) throws IOException { FileReader fr = null; //fr = new FileReader("C:UsersAsusDesktopITcpit305Slides Hind IOstreamsemployee.txt"); fr = new FileReader("C:/Users/Asus/Desktop/IT/cpit305/Slides Hind/ IOstreams/employee.txt"); int c = 0; System.out.println("My file separator is: " + File.separator); while ( fr.ready() ) { c = fr.read(); System.out.print((char) c); // print the character } fr.close() ; } }
  • 17. Example1: read from a file: Output >>java ReadFile My file separator is: Ahmad 22 Sara 30 Noor 12 17 • In this example we can open the file using the file separator of windows and Linux, however, the good practice is to use the right separator for every OS This is the content employee.txt
  • 18. Example1: read from a file without casting 18 import java.io.*; public class ReadFile{ public static void main(String[] args) throws IOException { FileReader fr = null; //fr = new FileReader("C:UsersAsusDesktopITcpit305Slides HindIOstreamsemployee.txt"); fr = new FileReader("C:/Users/Asus/Desktop/IT/cpit305/Slides Hind/IOstreams/employee.txt"); int c = 0; while ( fr.ready() ) { c = fr.read(); System.out.print(c); // print the code of the character System.out.print(" "); // print space } fr.close() ; } }
  • 19. Example1: read from a file without casting : Output >> java ReadFile 65 104 109 97 100 32 50 50 13 10 83 97 114 97 32 51 48 13 10 78 111 111 114 32 49 50 13 10 13 10 13 10 19 • These numbers are the character encoding of each character in the text file because we did not use casting to cast the integer c to its equivalent character
  • 20. Example2: write to a file 20 import java.io.*; public class WriteFile{ public static void main(String[] args) throws IOException { FileWriter fw = null; fw = new FileWriter(".employee.txt"); fw.write("Yara "); int c=65; fw.write(c); fw.close() ; } }
  • 21. Example2: write to a file Output Content of file before writing: Ahmad 22 Sara 30 Noor 12 21 Content of file after writing: Yara A • If we try to write to a file that doesn’t exist, the file will be created first, and no exception will be thrown • We have two problems in this example: 1. write method is overwriting the file. 2. Write(int c) writes the character represented by the integer c in the default character encoding
  • 22. Append to file instead of overwrite • If the FileWriter constructor take just one parameter, the file name, it will overwrite any existing file • FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file FileWriter fw = new FileWriter(".employee.txt", true); //appends to file FileWriter fw = new FileWriter(".employee.txt", false); //overwrites file 22
  • 23. How to write numbers in a text files • write(int c) expect an encoding number. Solutions: • We can use write(String) of FileWriter class 1. int c=65; fw.write(Integer.toString(c)); 2. int c=65; fw.write(c + ”n”); or fw.write(c + ””); • We can use PrintWriter to wrap the functionality of FileWriter 23
  • 24. Writing numbers using PrintWriter 24 import java.io.*; import java.nio.charset.*; public class WriteFile2{ public static void main(String[] args) throws IOException { PrintWriter fw = null; fw = new PrintWriter(new FileWriter(".employee.txt", true)); fw.print("Yara "); int c=65; fw.println(c); fw.close() ; } } This leads us to the concept of connected streams
  • 25. Writing numbers using PrintWriter: output Content of file before writing: Ahmad 22 Sara 30 Noor 12 25 Content of file after writing: Ahmad 22 Sara 30 Noor 12 Yara 65 • With PrintWriter, it is easier to format the output using the method printf • PrintWriter has many constructors: • one is as the previous example. It allows appending to the file. • PrintWriter(String fileName), this accept the fine name as string, but we cannot determine the append option
  • 26. Character encoding • Unicode is a character set of various symbols • Unicode contains code points (numeric value) for almost all represent-able graphic symbols in the world and it supports all major languages • https://unicode-table.com/en/#control-character • UTF-8, UTF-16 and UTF-32 are different ways to represent Unicode code points in byte format. They differ in the number of bytes needed to represent the character. • UTF-8 use 1, 2, 3, or 4 bytes • UTF-16 use 2 or 4 bytes • UTF-32 use 4 bytes (fixed width) 26
  • 27. 27
  • 28. Character encoding • For example, if the integer 1234 is saved in binary, it is written as the sequence of bytes 00 00 04 D2 (in hexadecimal notation) • In text format, it is saved as the string "1234“. • UTF-8: 31 32 33 34 • Utf-16: 0031 0032 0033 0034 • Although binary I/O is fast and efficient, it is not easily readable by humans • When we deal with text files, we need to consider the encoding scheme to read the right format of the file. Examples 3, 4, and 5 show some methods to determine a specific encoding scheme 28
  • 29. Example3: read from a text file using a Charset 29 import java.io.*; import java.nio.charset.*; public class ReadFileCharset{ public static void main(String[] args) throws IOException { System.out.println("The default: "+Charset.defaultCharset()); FileReader fr = null; fr = new FileReader(".employee.txt",StandardCharsets.UTF_8);//work in java 11 int c = 0; while ( fr.ready() ) { c = fr.read(); System.out.print((char) c); // print the character } fr.close() ; } }
  • 30. Example3: read from a text file using a Charset Output >>java ReadFileCharset The default: windows-1252 Ahmad 22 Sara 30 Noor 12 30 >>java ReadFileCharset The default: UTF-8 Ahmad 22 Sara 30 Noor 12 Result in jdk 17 and earlier versions of java Result in jdk 18 and newer versions of java
  • 31. Example4: write in a text file using a Charset 31 import java.io.*; import java.nio.charset.*; public class WriteFileCharset{ public static void main(String[] args) throws IOException { PrintWriter fw = null; //This constructor works in java 11 fw = new PrintWriter(new FileWriter(".employee.txt",StandardCharsets.UTF_8, true)); fw.print("Yara "); int c=65; fw.println(c); fw.close() ; } }
  • 32. Example5: read content of file and write it to another file 32 • Assume that we have the following text file: • employee16.txt • This file is encoded using UTF-16 charset • In Example5 we will read it in different charset to see the output
  • 33. Example5: read content of file and write it to another file 33 import java.io.*; import java.nio.charset.*; public class TestCharset{ public static void main(String[] args) throws IOException { System.out.println("The default: "+Charset.defaultCharset()); FileReader fr = null; fr = new FileReader(".employee16.txt",StandardCharsets.UTF_8);//work in java 11 FileWriter fw = null; //This constructor works in java 11 fw = new FileWriter(".employee3.txt",StandardCharsets.UTF_8, false); int c = 0; while ( fr.ready() ) { c = fr.read(); fw.write(c); //System.out.print((char) c); // print the character } fr.close() ; fw.close(); } }
  • 34. Example5: read content of file and write it to another file : output 34 • The output will be written in the file: employee3.txt which looks as following: • This shows the importance of using the right charset when we deal with files coming from different platforms
  • 35. Reading byte-oriented files • To read or write byte-oriented files use the two classes: • FileInputStream • FileOutputStream • Key differences between a FileReader and a FileInputStream : 1. The first difference is in their type hierarchy, FileReader extends from Reader class while FileInputStream is descendent of InputStream class. 2. The second difference is in their purpose. The FileReader is meant for reading text data while FileInputStream is for reading binary data. 3. The various overloaded read() method of FileReader can read one character at a time or multiple characters into an array while read() method of FileInputStream can read one byte at a time or multiple bytes in a byte array. 35
  • 36. Reading byte-oriented files • Images are type of the byte-oriented files; we cannot deal with them as text files • In the following example (Example6) we will read an image, change some of the bytes, then write the image with different name  Note: the modification is implemented randomly, i.e. does not consider the suitable format of jpg files. This example is only demonstration of the byte-oriented streams 36
  • 37. Example6: read and write images 37 import java.io.*; public class TestFileInputStream1 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(".javabig.jpg"); //To get how many bytes in the file int len = fis.available(); int[] temp = new int[len]; int i = 0; //total number of bytes in the image while (fis.available() > 0) { temp[i] = fis.read(); i++; } //random modification of the image for(int j=2000;j<3000;j++) temp[j]=33; //write the image in a new file FileOutputStream fos = new FileOutputStream(".myjavabig.jpg"); for (int j = 0; j < temp.length; j++) { fos.write(temp[j]); } fis.close() ; fos.close(); System.out.println("n byte[1000] and byte[2000]: "+(char)temp[1000]+ " "+(char)temp[2000] ); System.out.println("n the number of bytes is: "+len); } }
  • 38. Example6: read and write images output 38 >>java TestFileInputStream1 byte[1000] and byte[2000]: ? ! the number of bytes is: 66902
  • 39. Connected streams • Streams are wrapped to combine the various features of many streams • The DataInputStream has no methods to read from a file and the FileInputStream has no methods to read numeric types • Java allows you to combine these two types of streams into a filtered stream or connected streams • The FileInputStream knows how to read from a file. The DataInputStream knows how to read an InputStream into useful types (assemble bytes into more useful data types). • Connect the out end of the FileInputStream to the in end of the DataInputStream 39 DataInputStream FileInputStream File
  • 40. Connected streams • For example, if we wanted to read numbers from a file, we create a FileInputStream, to read the bytes from the file, and then a DataInputStream, which assemble bytes into more useful data types. • FileInputStream Fin = new FileInputStream(“java.dat”); DataInputStream Din = new DataInputStream(Fin); double num1 = Din.readDouble(); • Data streams do not represent new files but a more capable interface (i.e., they group bytes into more complex units) 40
  • 41. DataOutputStream (make binary files) • The code of the Example7 will store employee records as binary data • Assume that the record format is as following [ID(int) name(String) evaluation(double)] • The code in Example8 will read the employee records 41
  • 42. Example7: TestDataOutputStream.java 42 import java.io.*; public class TestDataOutputStream { public static void main(String[] args) throws IOException { //open the file in overwrite mode (not append) var dout= new DataOutputStream(new FileOutputStream(".employeeBinary.txt",false)); /* employeeBinary.txt has records of employees in the format: [ID(int) name(String) evaluation(double)] */ //first employee dout.writeInt(1); dout.writeUTF("Eman"); //write string dout.writeDouble(23.6); //second employee dout.writeInt(2); dout.writeUTF("Sarah"); //write string dout.writeDouble(22.5); dout.close(); } }
  • 43. Example7: TestDataOutputStream.java output 43 • Showing the file content in a text editor
  • 44. Example7: TestDataOutputStream.java output 44 • Showing the file content in a hexadecimal viewer
  • 45. Example7: TestDataOutputStream.java output 45 • writeInt(int) is writing integer in 4 bytes • writeDouble(double) is writing double in 8 bytes • writeUTF(string) writes two bytes of length information to the output stream, followed by the UTF-8 representation of every character in the string s
  • 46. Example8: TestDataInputStream.java 46 import java.io.*; public class TestDataInputStream { public static void main(String[] args) throws IOException { var din= new DataInputStream(new FileInputStream(".employeeBinary.txt")); /* employeeBinary.txt has records of employees in the format: [ID(int) name(String) evaluation(double)] */ int id; double eval; String str; while(din.available()>0) { id = din.readInt(); str = din.readUTF(); //read string eval = din.readDouble(); System.out.println("Employee ID#"+id+", name: "+str+", has evaluation = "+eval); } din.close(); } }
  • 47. Example8: TestDataInputStream.java output 47 >>java TestDataInputStream Employee ID#1, name: Eman, has evaluation = 23.6 Employee ID#2, name: Sarah, has evaluation = 22.5
  • 48. Connected streams: Buffering • You can add multiple capabilities by nesting the streams • If you desire buffering on your input streams to speed up data access, use for example, BufferedInputStream class object. • Not buffered: each byte is read/written from/to disk as soon as possible. By default, io streams are unbuffered • “little” delay for each byte • A disk operation per byte---higher overhead 48
  • 49. Connected streams: Buffering • Buffered: reading/writing in “chunks” • Some delay for some bytes • Assume 16-byte buffers: Reading: access the first 4 bytes, need to wait for all 16 bytes are read from disk to memory Writing: save the first 4 bytes, need to wait for all 16 bytes before writing from memory to disk • A disk operation per a buffer of bytes---lower overhead 49
  • 50. Connected streams: Buffering • Think of this as just another pipe in the chain, that adds buffering… DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream (“employee.dat”))); 50 DataInputStream FileInputStream File BufferedInputStrea m
  • 51. Buffering in java • There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams 51
  • 52. Buffering in java – possible constructors • Read from myfile.txt in char oriented, buffer size is bufSize var br= new BufferedReader(new FileReader(“myfile.txt”), bufSize) • Write (append) into myfile.txt in char oriented, buffer size is bufSize var bw= new BufferedWriter(new FileWriter(“myfile.txt”,true), bufSize) • Read from myfile.txt in binary oriented, buffer size is the default: 8 KB var bi= new BufferedInputStream(new FileInputStream(" myfile.txt")); • Write (overwrites) into myfile.txt in binary oriented, buffer size bufSize var bo= new BufferedOutputStream(new FileOutputStream(" myfile.txt"), bufSize); 52
  • 53. Example 9: using BufferedReader • In this example we will create object of the class BufferedReader with the size 10 KB. The default is 8 KB • It is best to use buffer sizes that are multiples of 1024 bytes. That works best with most built-in buffering in hard disks etc. • Except for adding buffering to Reader instances, a Java BufferedReader behaves pretty much like a Reader. The BufferedReader has one extra method though, the readLine() method. This method can be handy if you need to read input one line at a time 53
  • 54. Example 9: using BufferedReader 54 import java.io.*; public class ReadFileBuffered{ public static void main(String[] args) throws IOException { var fr = new FileReader(".employee.txt"); int bufferSize = 10 * 1024; var br=new BufferedReader(fr,bufferSize); String line; //int c; while ( br.ready() ) { /* c = br.read(); System.out.print((char)c); */ line = br.readLine(); System.out.println(line); } br.close() ; } }
  • 55. Example 9: using BufferedReader output 55 >>java ReadFileBuffered Ahmad 22 Sara 30 Noor 12
  • 56. Flushing buffered streams • It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer • To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered • Flush is called by default when we invoke close() of the output stream 56
  • 57. Example 10 and 11: using flush method • In example 10 we will use Buffered output stream and test the effect of flush on the output • In example 11 we will use unbuffered File output stream and test the effect of flush on the output 57
  • 58. Example 10: using BufferedOutputStream and flush 58 import java.io.*; public class TestBuffer2{ public static void main(String[] args) //throws IOException { // using (try-with-resources) we dont need to call close try( OutputStream os = new FileOutputStream("test.txt"); BufferedOutputStream buffer = new BufferedOutputStream(os); InputStream is = new FileInputStream("test.txt"); ) { buffer.write('A'); buffer.write('B'); // read count of what we wrote without flush System.out.println("count before flush: " + is.available()); buffer.flush(); // read count of what we wrote after flush System.out.println("count after flush: " + is.available()); } catch (Exception ex) { ex.printStackTrace(); } } }
  • 59. Example 10: using BufferedOutputStream and flush output 59 >>java TestBuffer2 count before flush: 0 count after flush: 2
  • 60. Example 11: using OutputStream and flush 60 import java.io.*; public class TestBuffer3{ public static void main(String[] args) throws IOException { // using (try-with-resources) we dont need to call close try( OutputStream os = new FileOutputStream("test.txt"); InputStream is = new FileInputStream("test.txt"); ) { os.write('A'); os.write('B'); // read count of what we wrote without flush System.out.println("count before flush: " + is.available()); os.flush(); // read count of what we wrote after flush System.out.println("count after flush: " + is.available()); } } }
  • 61. Example 11: using OutputStream and flush output 61 >>java TestBuffer3 count before flush: 2 count after flush: 2
  • 62. Random Access files • The RandomAccessFile class lets you read or write data anywhere in a file. • Disk files are random access, but input/output streams that communicate with a network socket are not • RandomAccessFile class Open a random-access file either for reading only or for both reading and writing. 62
  • 63. Random Access files • To read: RandomAccessFile rf = new RandomAccessFile(“employee.txt", "r"); • To read and write: RandomAccessFile rf = new RandomAccessFile(“employee.txt", "rw"); 63
  • 64. Random Access files • A randomaccess file has a file pointer that indicates the position of the next byte to be read or written • The getFilePointer method and seek method gets/sets the file pointer to a byte position within the file • The RandomAccessFile class implements both the DataInput and DataOutput interfaces. For example, use readInt / writeInt ( readXXX() / writeXXX() where XXX are primitive data types) • Also it has the method readLine() to read each line of a text file 64
  • 65. Random Access files • To determine the number of bytes at a file use length method int nbytes = (int) rf.length(); // length in bytes int nrecords = nbytes / RECORD_SIZE; • Where RECORD_SIZE is the size of each record in the file 65
  • 66. Random Access files • To position the file pointer to the third record: int i = 3; rf.seek((i – 1) * RECORD_SIZE); • Then we can read or write at that position • The RandomAccessFile is more useful when we have records of fixed length 66
  • 67. Random Access files – try with resources • We can open the files in a block called try-with-resources • It is an alternative for try-catch-finally blocks • It will close the file automatically without close method and optionally you can add catch or finally blocks 67
  • 68. Example12: TestRandomAccess1 page 1 68 import java.io.*; import java.util.*; import java.nio.charset.*; public class TestRandomAccess1{ public static void main(String[] args) throws IOException { var staff = new Employee[3]; staff[0] = new Employee(1,"Sara", 7500); staff[1] = new Employee(2,"Noor", 5000); staff[2] = new Employee(3,"Amal", 4000); String temp; // Writing employee records into employee.txt as records of fixed length try (var out = new FileWriter(".//employee.txt",StandardCharsets.UTF_8)) { for (Employee e : staff) { temp=Integer.toString(e.getID()); out.write(fixedString(temp,Employee.ID_SIZE)); out.write(fixedString(e.getName(),Employee.NAME_SIZE)); temp=Double.toString(e.getSalary()); out.write(fixedString(temp,Employee.SALARY_SIZE)); out.write("n"); //test 'n' } }
  • 69. Example12: TestRandomAccess1 page 2 69 try (var rf = new RandomAccessFile("employee.txt", "rw")) { // retrieve all records into a new array // compute the array size System.out.println("file length= "+rf.length()+" Bytes"); int n = (int)(rf.length() / Employee.RECORD_SIZE); var newStaff = new Employee[n]; System.out.println("number of employees= "+n); System.out.println("Record size="+ Employee.RECORD_SIZE); // read employees in reverse order for (int i = n - 1; i >= 0; i--) { rf.seek(i * Employee.RECORD_SIZE); String str = rf.readLine(); StringTokenizer tokens = new StringTokenizer(str); int tokenID= Integer.parseInt(tokens.nextToken()); String tokenName=tokens.nextToken(); double tokenSalary= Double.parseDouble(tokens.nextToken()); newStaff[i] = new Employee(tokenID,tokenName,tokenSalary); } // print the newly read employee records System.out.println("Emplyees reading by RandomAccess class: "); for (Employee e : newStaff) System.out.println(e);
  • 70. Example12: TestRandomAccess1 page 3 70 // change the second record int r=2; rf.seek((r - 1) * Employee.RECORD_SIZE); String str = rf.readLine(); String[] tokens = str.split("s+"); int tokenID= Integer.parseInt(tokens[0]); String tokenName=tokens[1]; double tokenSalary= Double.parseDouble(tokens[2]); tokenSalary*=2; System.out.println("We doubled the salary of this employee: "+str); rf.seek(((r - 1) * Employee.RECORD_SIZE) + (Employee.ID_SIZE + Employee.NAME_SIZE) ); temp=Double.toString(tokenSalary); rf.writeBytes(fixedString(temp,Employee.SALARY_SIZE)); } }
  • 71. Example12: TestRandomAccess1 page 4 71 public static String fixedString(String s, int size) { char[] array=new char[size]; for (int i = 0; i < size; i++) { if (i < s.length()) array[i] = s.charAt(i); else array[i]=' '; } return new String(array); } }
  • 72. Example12: TestRandomAccess1 page 5 72 //-------Employee class-- class Employee { //following constants used only to save records in the text file public static final int NAME_SIZE = 10; public static final int ID_SIZE = 4; public static final int SALARY_SIZE = 10; public static final int RECORD_SIZE = (NAME_SIZE + ID_SIZE + SALARY_SIZE) + 1; //last 1 is for n private int id; private String name; private double salary; public Employee() {} public Employee(int i, String n, double s) { id=i; name = n; salary = s; } public String getName() { return name; }
  • 73. Example12: TestRandomAccess1 page 6 73 public double getSalary() { return salary; } public int getID() { return id; } public String toString() { return "Employee" //"Employee" + "[name=" + name + ",salary=" + salary + ",ID=" + id + "]"; } }
  • 74. Example12: TestRandomAccess1 output 74 >>java TestRandomAccess1 file length= 75 Bytes number of employees= 3 Record size=25 Emplyees reading by RandomAccess class: Employee[name=Sara,salary=7500.0,ID=1] Employee[name=Noor,salary=5000.0,ID=2] Employee[name=Amal,salary=4000.0,ID=3] We doubled the salary of this employee: 2 Noor 5000.0
  • 76. Scanner class • It is a simple text scanner which can parse primitive types and strings using regular expressions • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace • The resulting tokens may then be converted into values of different types using the various next methods 76
  • 77. Scanner class • It has many constructors, such as: • Scanner(File source) produces values scanned from a file • Scanner(InputStream source) produces values scanned from input stream such as System.in • Scanner(String source) produces values scanned from string 77
  • 78. Scanner class • We can change the default delimiter using the method: useDelimiter • To set single delimiter, we use simple string that include the delimiter • sc.useDelimiter(“,”) will split the string based on the occurrence of , • sc.useDelimiter(“//”) will split the string based on the occurrence of // • To set multiple delimiters, we should use regex: 78
  • 79. Scanner class - regex • Regex is a regular expression defines a search pattern for strings • The search pattern can be anything from a simple character, a fixed string or a complex expression containing special characters 79
  • 80. Scanner class - regex • To use multiple characters in regex we use | • Example, sc.useDelimiter(“, | .”) will make the delimiter as , or . • The dot symbol (.) has special meaning for regex (it matches any single character) so we need to escape it with to be used literally. In addition, is escape character in java strings so we need to escape it by another 80
  • 81. Example14: TestScannerTokens 81 import java.io.*; import java.util.*; public class TestScannerTokens{ public static void main(String[] args) throws IOException { Scanner sc1 = new Scanner("that, that is, is"); while(sc1.hasNext()) System.out.println("Tokens of sc1: <" + sc1.next() + ">"); System.out.println(" -------- "); Scanner sc2 = new Scanner("that, that is, is"); sc2.useDelimiter(","); while(sc2.hasNext()) System.out.println("Tokens of sc2: <" + sc2.next() + ">"); System.out.println(" -------- "); Scanner sc3 = new Scanner("http://192.173.15.36:8084/abc"); sc3.useDelimiter(":|/|."); //sc3.useDelimiter("://|/|:|."); while(sc3.hasNext()) System.out.println("Tokens of sc3: <" + sc3.next() + ">"); System.out.println(" -------- "); Scanner sc4 = new Scanner("abcdef"); sc4.useDelimiter(""); //just to make as delimiter while(sc4.hasNext()) System.out.println("Tokens of sc4: <" + sc4.next() + ">"); }}
  • 82. Example14: TestScannerTokens output 82 >>java TestScannerTokens Tokens of sc1: <that,> Tokens of sc1: <that> Tokens of sc1: <is,> Tokens of sc1: <is> -------- Tokens of sc2: <that> Tokens of sc2: < that is> Tokens of sc2: < is> -------- Tokens of sc3: <http> Tokens of sc3: <> Tokens of sc3: <> Tokens of sc3: <192> Tokens of sc3: <173> Tokens of sc3: <15> Tokens of sc3: <36> Tokens of sc3: <8084> Tokens of sc3: <abc> -------- Tokens of sc4: <abc> Tokens of sc4: <def>
  • 83. Example12: TestScannerTokens output • Why we need four backslashes to have delimiter? • The reason behind this is that your string is de-escaped twice. Once at compile time as every other string literal in the Java language, and once at the parsing by the regex class. That means, after the first step it is escaped once, so the regex parser gets two backslashes . The regex parser will de-escape that too, and will match a single character 83
  • 84. String.split method • The split method in String class is working using regex, i.e. exactly like Scanner tokenization • In the following slide we will repeat the Scanner example but with split method, and we will use exactly the same regular expressions 84
  • 85. Example15: TestSplitTokens 85 import java.io.*; import java.util.*; public class TestSplitTokens{ public static void main(String[] args) throws IOException { int i; String st1="that, that is, is"; String[] tokens1=st1.split("s"); i=0; while(i<tokens1.length) System.out.println("Tokens of st1: <"+tokens1[i++] + ">"); System.out.println(" -------- "); String st2="that, that is, is"; String[] tokens2=st2.split(","); i=0; while(i<tokens2.length) System.out.println("Tokens of st2: <"+tokens2[i++] + ">"); System.out.println(" -------- "); String st3="http://192.173.15.36:8084/abc"; String[] tokens3=st3.split(":|/|."); i=0; while(i<tokens3.length) System.out.println("Tokens of st3: <"+tokens3[i++] + ">"); System.out.println(" -------- "); String st4="abcdef"; String[] tokens4=st4.split(""); i=0; while(i<tokens4.length) System.out.println("Tokens of st4: <"+tokens4[i++] + ">"); }}
  • 86. Example15: TestSplitTokens output 86 >>java TestSplitTokens Tokens of st1: <that,> Tokens of st1: <that> Tokens of st1: <is,> Tokens of st1: <is> -------- Tokens of st2: <that> Tokens of st2: < that is> Tokens of st2: < is> -------- Tokens of st3: <http> Tokens of st3: <> Tokens of st3: <> Tokens of st3: <192> Tokens of st3: <173> Tokens of st3: <15> Tokens of st3: <36> Tokens of st3: <8084> Tokens of st3: <abc> -------- Tokens of st4: <abc> Tokens of st4: <def>
  • 87. Object serialization • Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory • The byte stream created is platform independent. So, the object serialized on one platform can be sent on network or saved to database and deserialized on a different platform • To make a Java object serializable, its class should implement the java.io.Serializable interface 87
  • 88. Object serialization • The Serializable interface has no methods, so you don’t need to change your classes in any way • ObjectOutputStream class is used to write objects in the serialization process using the method writeObject • ObjectInputStream class is used to read objects in the deserialization process using the method readObject • When you use readObject method, you should explicitly cast the loaded object 88
  • 89. Serialization • It is possible to write or read array of objects at one call for the writeObject and readObject methods • Behind the scenes, an ObjectOutputStream looks at all the fields of the objects and saves their contents based on their type • Note: static fields belong to a class (as opposed to an object) and are not serialized 89
  • 90. Example16: TestSerialize 90 import java.io.*; public class TestSerialize{ public static void main(String[] args) throws IOException, ClassNotFoundException { var sara = new Employee("Sara", 5000); var nora = new Employee("Nora", 8000); var amal = new Employee("Amal", 9000); var staff = new Employee[3]; staff[0] = sara; staff[1] = nora; staff[2] = amal; try (var out = new ObjectOutputStream(new FileOutputStream("employee.dat"))) { out.writeObject(staff); } // retrieve all records into a new array try (var in = new ObjectInputStream(new FileInputStream("employee.dat"))) { var newStaff = (Employee[]) in.readObject(); for (Employee e : newStaff) System.out.println(e); } }}
  • 91. Example16: TestSerialize 91 class Employee implements Serializable { private String name; private double salary; public Employee() {} public Employee( String n, double s) { name = n; salary = s; } public String getName() { return name; } public double getSalary() { return salary; } public String toString() { return "Employee" + "[name=" + name + ",salary=" + salary + "]";
  • 92. Example16: TestSerialize output 92 >>java TestSerialize Employee[name=Sara, salary=5000.0] Employee[name=Nora, salary=8000.0] Employee[name=Amal, salary=9000.0]
  • 93. Java.nio.file package - file system management • The java.io.File class was the old mechanism used for file I/O, but it had several drawbacks: • Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. • The rename method didn't work consistently across platforms • There was no real support for symbolic links (in Linux) • More support for metadata was desired, such as file permissions, file owner, and other security attributes • Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. • The good alternative of java.io.File is java.nio.file.Path 93
  • 94. Java.nio.file package – Path and Paths • To work with Files, we need the following terms: Path: This is the interface that replaces java.io.File class as the representation of a file or a directory when we work in Java NIO. Paths: This class contains a static methods to create Path instance. • java.nio.file.Path interface is just like the old java.io.File class. Path represents location of the file. 94
  • 95. Java.nio.file package – file system management • Java Files class contains static methods that work on files and directories • This class is used for basic file operations like create, read, write, copy and delete the files or directories of the file system. These methods mostly works on Path instance 95
  • 96. How to Create Path • We can create an object of Path by calling Paths.get(String first, String... more) method of Paths class such as: Path path1 = Paths.get("D:/data/file.txt"); • When we create a Path to new file, it does not create actual file until we create it using Files.createFile(Path filePath) 96
  • 97. Create new directory • To create a new directory, call: Files.createDirectory(path) • All but the last component in the path must already exist. If directory is already existing, then it will throw nio.file.FileAlreadyExistsException • To create intermediate directories as well, use: Files.createDirectories(path); Creates a directory by creating all nonexistent parent directories first. • These two methods will return the path of the created directory 97
  • 98. Create empty file • You can create an empty file with: • Files.createFile(path); • The call throws an exception if the file already exists • It will return the path of the created file 98
  • 99. Copying, moving, and deleting Files • To copy a file from one location to another, simply call: Files.copy(fromPath, toPath); • To move the file (that is, copy and delete the original), call: Files.move(fromPath, toPath); • The copy or move will fail if the target (toPath) exists with the checked exception FileAlreadyExistsException 99
  • 100. Copying, moving, and deleting Files • If you want to overwrite an existing target, use the REPLACE_EXISTING option. You can supply both like this: Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING); • StandardCopyOption is enum that contains some constants to determine the options of file copying and moving 100
  • 101. Copying, moving, and deleting Files • Finally, to delete a file, simply call Files.delete(path); • This method throws an exception if the file doesn’t exist, so instead you may want to use: boolean deleted = Files.deleteIfExists(path); • The deletion methods can also be used to remove an empty directory 101
  • 102. Using Files.writeString • The method writeString is a static method in Files class with the following signature: public static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOException • CharSequence is an interface that is implemented by String class • OpenOption is an interface that is implemented by the enum StandardOpenOption • Some of the options in StandardOpenOption are: • APPEND: Append to the existing file • CREATE: Create a new file if it does not exist. 102
  • 103. Getting file information • The following static methods return a Boolean value to check a property of a path • exists • isHidden • isReadable, isWritable, isExecutable • isRegularFile, isDirectory • The size method returns the number of bytes in a file. long fileSize = Files.size(path); 103
  • 104. Visiting Directory Entries • The static Files.list method returns a Stream<Path> that reads the entries of a directory • Since reading a directory involves a system resource that needs to be closed, you should use a try block • try (Stream<Path> entries = Files.list(pathToDirectory)) • The list method does not enter subdirectories. To process all descendants of a directory, use the Files.walk method instead. • try (Stream<Path> entries = Files.walk(pathToDirectory)) 104
  • 105. Example 17: TestFiles.java page 1 105 import java.io.*; import java.nio.file.*; import java.util.stream.Stream; public class TestFiles{ public static void main(String[] args) throws IOException { // initialize Path object of a directory Path pathDirectory=Paths.get(".MyDirectory"); //creat the directory Path createdDir = Files.createDirectory(pathDirectory); System.out.println("The created directory: "+createdDir); // initialize Path object of a txt file Path path1=Paths.get(".MyDirectorymyfile1.txt"); //creat the file Path createdFile1 = Files.createFile(path1); System.out.println("The first created file: "+createdFile1); //writing to the created file (myfile1.txt) Files.writeString(path1,"some test content in myfile1.txt"); //write will close the file itself
  • 106. Example 17: TestFiles.java page 2 106 //intialize another Path object Path path2=Paths.get(".MyDirectorymyfile2.txt"); Path createdFile2 = Files.writeString(path2,"some test content in myfile2.txt",StandardOpenOption.CREATE, StandardOpenOption.APPEND); System.out.println("The second created file: "+createdFile2); //copying myfile2.txt to the parent directory and name it myfile3.txt Path target = Paths.get(".myfile3.txt"); Files.copy(path2, target); System.out.println("Target file Path : "+target); System.out.println("Content of target: n"+new String(Files.readAllBytes(target)));
  • 107. Example 17: TestFiles.java page 3 107 //listing content of current directory Path current = Paths.get("."); try (Stream<Path> mylist = Files.walk(current)) { System.out.println("n Following are the files end with .java n"); mylist.forEach( p -> { String s = p.toString(); if (s.matches(".*.java")) System.out.println(s); } ); }//end of try-with-resources try (Stream<Path> mylist = Files.walk(current)) { System.out.println("n Following are all the content of current directory n"); mylist.forEach( p ->System.out.println(p)); }//end of try-with-resources } }
  • 108. Example 17: TestFiles.java output 108 C:UsersAsusDesktopITCPIT305Slides HindIOstreams>java TestFiles The created directory: .MyDirectory The first created file: .MyDirectorymyfile1.txt The second created file: .MyDirectorymyfile2.txt Target file Path : .myfile3.txt Content of target: some test content in myfile2.txt Following are the files end with .java .ExampleError.java .ReadFile.java .ReadFileBuffered.java .ReadFileCharset.java .TestArabic.java .TestBuffer1.java .TestBuffer2.java .TestBuffer3.java .TestCharset.java .TestDataInputStream.java .TestDataOutputStream.java .TestFileInputStream.java ……..
  • 109. Example 17: TestFiles.java output 109 Following are all the content of current directory . .iodata.txt .IOStream.pptx .javabig.jpg .MyDirectory .MyDirectorymyfile1.txt .MyDirectorymyfile2.txt .myfile3.txt .myjavabig.jpg .myjavabigSector.jpg .ReadFile.class .ReadFile.java .ReadFileBuffered.class .ReadFileBuffered.java .ReadFileCharset.class ……
  • 110. Streams • Interface Stream<T> • A stream is not a data structure instead it takes input from other java objects • Hence, it is a sequence of elements supporting various methods such as forEach • forEach: used to iterate through every element of the stream • It has one argument with the type: Consumer interface • Consumer is a functional interface with one abstract method (void accept​(T t)), so can be used for lambda expression 110
  • 111. Lambda expression • Lambda expressions basically express instances of functional interfaces (An interface with single abstract method). • lambda expressions implement the only abstract function and therefore implement functional interfaces • It provides the following functionalities: • Enable to treat functionality as a method argument • A function that can be created without belonging to any class 111
  • 112. Lambda expression • The simplest lambda expression contains a single parameter and an expression: • parameter -> expression • To use more than one parameter, wrap them in parentheses: • (parameter1, parameter2) -> expression • Expressions are limited. They cannot contain variables, assignments or statements such as if or for. In order to do more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement. • (parameter1, parameter2) -> { code block } 112
  • 113. Lambda expression • If a lambda expression has no parameters, you still supply empty parentheses: • () -> { code block } • If the parameter types of a lambda expression can be inferred, you can omit them • Any lambda expression can be replaced with an object of anonymous class that implement the functional interface • Also, any lambda expression can be replaced with an object of inner class that implement the functional interface 113
  • 114. Example 18: printing content of directory using anonymous class instead of Lambda expression 114 import java.io.*; import java.nio.file.*; import java.util.function.*; import java.util.stream.Stream; public class TestFiles1{ public static void main(String[] args) throws IOException { //listing content of current directory Path current = Paths.get("."); try (Stream<Path> mylist = Files.walk(current)) { System.out.println("n Following are all the content of current directory n"); mylist.forEach( new Consumer<Path>() { public void accept(Path p){ System.out.println(p); }//end of accept method });//end of forEach call }//end of try-with-resources } }
  • 115. Example 18: TestFiles1.java output 115 C:UsersAsusDesktopITCPIT305Slides HindIOstreams>java TestFiles1 Following are all the content of current directory . .iodata.txt .IOStream.pptx .javabig.jpg .MyDirectory .MyDirectorymyfile1.txt .MyDirectorymyfile2.txt .myfile3.txt .myjavabig.jpg .myjavabigSector.jpg .ReadFile.class .ReadFile.java .ReadFileBuffered.class .ReadFileBuffered.java .ReadFileCharset.class ……
  • 116. Example 19: repeat Ex18 using inner class 116 public class TestFiles2{ public static void main(String[] args) throws IOException { var obj = new TestInner(); obj.printDirectories(); } } class TestInner { public TestInner() {} public void printDirectories() throws IOException { //listing content of current directory Path current = Paths.get("."); try (Stream<Path> mylist = Files.walk(current)) { System.out.println("n Following are all the content of current directory n"); var myConsumer = new myInner(); mylist.forEach(myConsumer); }//end of try-with-resources } private class myInner implements Consumer<Path> { public myInner() {} public void accept(Path p){ System.out.println(p); }//end of accept method }// end of inner class }
  • 117. Example 19: TestFiles2.java output 117 C:UsersAsusDesktopITCPIT305Slides HindIOstreams>java TestFiles2 Following are all the content of current directory . .iodata.txt .IOStream.pptx .javabig.jpg .MyDirectory .MyDirectorymyfile1.txt .MyDirectorymyfile2.txt .myfile3.txt .myjavabig.jpg .myjavabigSector.jpg .ReadFile.class .ReadFile.java .ReadFileBuffered.class .ReadFileBuffered.java .ReadFileCharset.class ……
  • 118. Class files created by compiler in the previous two examples 118
  • 119. File locking • When multiple simultaneously executing programs need to modify the same file, they need to control its access in some way, or the file can easily become damaged. • File locks can solve this problem. A file lock controls access to a file or a range of bytes within a file 119
  • 120. File locking – a possible scenario • Suppose your application saves a configuration file with user preferences. If a user invokes two instances of the application. • It could happen that both of them want to write the configuration file at the same time. • In that situation, the first instance should lock the file. • When the second instance finds the file locked, it can decide to wait until the file is unlocked or simply skip the writing process 120
  • 121. File locking • java programming language supports file locking with the java.nio package • First step to lock file is to get a channel for the required file • A channel is an abstraction for a disk file that lets you access operating system features such as memory mapping and file locking 121
  • 122. File locking Path path1 = Paths.get(“./file.txt"); FileChannel channel1 = FileChannel.open(path1, StandardOpenOption.READ); • By default, the channel is opened for reading, so, the second argument is optional. The parameter options can be READ, WRITE, or APPEND in the StandardOpenOption enumeration. 122
  • 123. File locking • Second step to lock a file, call either the lock or tryLock methods of the FileChannel class Path path1 = Paths.get(“./file.txt"); FileChannel channel1 = FileChannel.open(path1, StandardOpenOption.WRITE); FileLock lock1 = channel1.lock(); Or FileLock lock2 = channel1.tryLock(); 123
  • 124. File locking • The first method [lock()] blocks until the lock becomes available. The second method [tryLock()] returns immediately, either with the lock or with null if the lock is not available. • The file remains locked until the channel is closed: channel1.close(); • or the release method is invoked on the lock: lock1.release(); 124
  • 125. File locking • To have a shared lock on only part of the file, we can use the following syntax of lock method FileLock lock1 = channel1.lock(long start, long size, boolean shared) • Or FileLock lock1 = channel1.tryLock(long start, long size, boolean shared) • The parameter shared is true for a shared lock, false for an exclusive lock. The shared lock allows multiple processes to read from the file, while preventing any process from acquiring an exclusive lock 125
  • 126. File locking – Exclusive lock • To get an exclusive lock, we must use a writable FileChannel. For example: try ( FileChannel channel = FileChannel.open(path, StandardOpenOption.APPEND); FileLock lock = channel.lock() ) { // write to channel } • If you try to acquire an exclusive lock of read-only channel, the lock() method will throw an Exception 126
  • 127. File locking – shared lock • Shared locks are also called read locks. Hence, to get a read lock, we must use a readable FileChannel. For example: try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ); FileLock lock = channel.lock(0, channel.size(), true)) { // read from the channel } • If you try to acquire a shared lock of writable channel, the lock() method will throw an Exception 127
  • 128. File locking • Be sure to unlock the lock when you are done. • The unlock is best done with a try-with-resources statement: try (FileLock lock1 = channel1.lock()) { access the locked file } • Try-with-resources will release the lock when its block end 128
  • 129. To summarize Input Output DataInputStream(InputStream in) DataOutputStream(OutputStream out) 1- FileInputStream(String name) 2- FileInputStream(File file) 1- FileOutputStream(String name) 2- FileOutputStream(String name, boolean append) 3- FileOutputStream(File file) 4- FileOutputStream(File file, boolean append) 1- FileReader(String fileName) 2- FileReader(File file) 1- FileWriter(String fileName) 2- FileWriter(String fileName, boolean append) 3- FileWriter(File file) 4- FileWriter(File file, boolean append) 129
  • 130. To summarize Input Output 1- BufferedInputStream(InputStream in) 2- BufferedInputStream(InputStream in, int size) 1- BufferedOutputStream(OutputStream out) 2- BufferedOutputStream(OutputStream out, int size) 1- BufferedReader(FileReader in) 2- BufferedReader(FileReader in, int size) 1- BufferedWriter(FileWriter out) 2- BufferedWriter (FileWriter out, int size) ObjectInputStream(InputStream in) ObjectOutputStream(OutputStream out) 1- RandomAccessFile(String file, String mode) 2- RandomAccessFile(File file, String mode) 130

Editor's Notes

  • #8: Ref when we got EOFException or special values such as -1: https://stackoverflow.com/questions/18451232/eofexception-how-to-handle https://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html#:~:text=Class%20EOFException&text=Signals%20that%20an%20end%20of,rather%20than%20throwing%20an%20exception. https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
  • #17: boolean ready(): Tells whether this stream is ready to be read, i.e. if bytes are available to be read from the underlying stream.
  • #30: This reference about the default charset in java: https://medium.com/@andbin/jdk-18-and-the-utf-8-as-default-charset-8451df737f90
  • #32: - More about StandardCharsets https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/nio/charset/StandardCharsets.html - About using utf-8 for Arabic symbols: https://stackoverflow.com/questions/2996475/what-character-encoding-should-i-use-for-a-web-page-containing-mostly-arabic-tex#:~:text=UTF%2D8%20can%20store%20the,fine%20to%20use%20for%20Arabic.
  • #57: Reference: https://docs.oracle.com/javase/tutorial/essential/io/buffers.html
  • #84: Good examples of Regex: https://www.javatpoint.com/java-regex
  • #91: ClassNotFoundException is required by the method readObject() because its signature throws this checked exception. If we don’t throws this exception we will get compile time exception
  • #92: If the class Employee does not implement Serializable interface, we will get runtime exception (NotSerializableException)
  • #112: Good references: Book, volume 1 (chapter 6): https://www.javatpoint.com/java-lambda-expressions http://tutorials.jenkov.com/java/lambda-expressions.html
  • #113: Good references: Book, volume 1 (chapter 6): https://www.javatpoint.com/java-lambda-expressions http://tutorials.jenkov.com/java/lambda-expressions.html
  • #114: Good references: Book, volume 1 (chapter 6): https://www.javatpoint.com/java-lambda-expressions http://tutorials.jenkov.com/java/lambda-expressions.html
  • #115: Good references: Book, volume 1 (chapter 6): https://www.javatpoint.com/java-lambda-expressions http://tutorials.jenkov.com/java/lambda-expressions.html
  • #117: We should have the import commands as Example 18