0% found this document useful (0 votes)
11 views29 pages

Chapter 5 IO Files

Chapter 5 discusses the File class in Java, which allows for the permanent storage of data by managing files on disk. It covers the differences between text and binary files, the concept of streams for input and output operations, and the various classes and methods associated with file handling in Java. Additionally, it highlights the importance of file properties and permissions, as well as providing examples of reading and writing data using different stream classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views29 pages

Chapter 5 IO Files

Chapter 5 discusses the File class in Java, which allows for the permanent storage of data by managing files on disk. It covers the differences between text and binary files, the concept of streams for input and output operations, and the various classes and methods associated with file handling in Java. Additionally, it highlights the importance of file properties and permissions, as well as providing examples of reading and writing data using different stream classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter-5

Streams and File I/O Streams


The File Class
 Data stored in variables, arrays, and objects are
temporary; they are lost when the program terminates.
 To permanently store the data created in a program, you need to
save them in a file on a disk or a CD.
 The file can be transported and can be read later by other
programs.
 Since data are stored in files, this section introduces how
to use the File class to obtain file properties and to delete
and rename files.
 The next section introduces how to read/write data from/to
text files.
Cont…
 Every file is placed in a directory in the file system.
 An absolute file name contains a file name with its
complete path and drive letter.
 For example, c:\book\Welcome.java is the absolute file
name for the file Welcome.java on the Windows operating
system.
 Here c:\book is referred to as the directory path for the
file.
 Absolute file names are machine dependent.
Cont…
 On the Unix platform, the absolute file name may be
/home/liang/book/Welcome.java, where /home/liang/book
is the directory path for the file Welcome.java.
 The File class is intended to provide an abstraction that
deals with most of the machine dependent complexities of
files and path names in a machine-independent fashion.
 The File class contains the methods for obtaining file
properties and for renaming and deleting files.
Cont…
 Text files
 contain data that can be read in a text editor because the data has
been encoded using a scheme such as ASCII or Unicode.
 Some text files are data files that contain facts and figures, such
as a payroll file that contains employee numbers, names, and
salaries; some files are program files or application files that
store software instructions.
 Binary files
 contain data that has not been encoded as text.
 Their contents are in binary format, which means that you cannot
understand them by viewing them in a text editor.
 Examples include images, music, and the compiled program files
with a .class extension
Cont…
 Computer files are the electronic equivalent of paper
files stored in file cabinets.
 When you work with stored files in an application,
you typically perform the following tasks:
o Determining whether and where a path or file exists
o Opening a file
o Writing to a file
o Reading from a file
o Closing a file
o Deleting a file
Cont…
 Most businesses generate and use large quantities of data
every day.
 You can store data in variables within a program, but such
storage is temporary.
 When the application ends, the variables no longer exist and
the data values are lost.
 Variables are stored in the computer’s main or primary
memory (RAM).
 When you need to retain data for any significant amount of
time, you must save the data on a permanent, secondary
storage device, such as a disk.
 character-field-record-file
Cont…
 When people view a file as a series of records, with each
record containing data fields, Java does not automatically
attribute such meaning to a file’s contents.
 Instead, Java simply views a file as a series of bytes.
 When you perform an input operation in an application,
you can picture bytes flowing into your program from an
input device through a stream, which functions as a
pipeline or channel.
 When you perform output, some bytes flow out of your
application through another stream to an output device.
Cont…
 Most fundamental I/O in Java is based on streams.
 A stream represents a flow of data with a writer at one
end and a reader at the other.
 When you are working with the java.io package to
perform terminal input and output, reading or writing
files, or communicating through sockets in Java, you are
using various types of streams.
 streams are oriented around bytes or characters while
channels are oriented around “buffers” containing those
data types—yet they perform roughly the same job.
Cont…
 Input and output operations are usually the slowest in any
computer system because of limitations imposed by the
hardware.
 For that reason, professional programs often employ
buffers.
 A buffer is a memory location where bytes are held after
they are logically output, but before they are sent to the
output device
Streams
 Java IO Streams
 Byte Oriented Streams
 Character Oriented Streams
 Byte Stream Classes
 FileInputStream, FileOutputStream
 BufferedInputStream, BufferedOutputStream
 DataInputStream, DataOutputStream
 PrintStream
 Character Stream Classes
 FileReader, FileWriter
 BufferedReader, BufferedWriter
What to read and write?
 Input streams read bytes and output streams write bytes.
 Readers read characters and writers write characters.
 Therefore, to understand input and output, you first need a solid
understanding of how Java deals with bytes, integers, characters, and other
primitive data
 Integers: byte (8 bit) , Short (16 bits), Int (32 bits), Long (64 bits)
 Java support only int literal, no byte and short are available
 byte b=42 and short s=24000; //compiler does conversion here
 Byte b1=5, b2=7; Byte b3=b1+b2; is also error as when bytes are added it
gives integer output and that can’t be assigned to byte
Data IO in java
 Standard output (to Screen/Console)
 System.out
 System.out.println(“Hello”);
 System.err
 System.err.println(“Stop”);

 Standard input (from keyboard)


 System.in
 System.in.read();

 Java io files are available in package java.io.*;


 Java’s stream-based I/O is based on four abstract classes:
 Byte Streams (InputStream, OutputStream) – used when working with bytes or
other binary objects
 Character Streams (Reader, and Writer) – used when working with characters
or strings
Input and Output Byte Streams
 Programs use byte streams to perform input and output of 8-bit
bytes.
 The byte stream classes provide a rich environment for handling
byte-oriented I/O.
 A byte stream can be used with any type of object, including
binary data. This versatility makes byte streams important to
many types of programs.
 All byte stream classes are descended from InputStream and
OutputStream
 Every things is read as byte form (signed integer that ranges from
-128 to 127)
 Java stream classes accept and return int which are internally
converted to byte
Input Stream
 InputStream is an abstract class that defines Java’s model of streaming byte input
 Most of the methods in this class will throw an IOException when an I/O error
occurs
 We use the derived classes to perform input functions. Some functions are:
o read() read a byte from input stream
o read(byte[] b) read a byte array from input into b
o read(byte[]b, int n, int m) read m bytes into b from nth byte
o available() gives number of bytes in
input
o skip(n) skips n bytes from input stream
o reset() goes back to beginning of stream
o close() closes the input stream
 Read() method returns actual number of bytes that were successfully read or-1 if end
of the file is reached.
Output Stream
 OutputStream is an abstract class that defines streaming byte
output.
 Most of the methods in this class return void and throw an
IOException in the case of I/O errors.
 OutputStream has following methods:
o write() write a byte to output stream
o write(byte[] b) write all bytes in b into output stream
o write(byte[] b, int n, int m) write m bytes from array b
from n’th
o close() Closes the output stream
o flush() flushes the output stream
File Input Stream
 FileInputStream class creates an InputStream that you can
use to read bytes from a file.
 Constructors:
o FileInputStream(String filePath)
o FileInputStream(File fileObj)
 Code
o FileInputStream f0 = new FileInputStream("/autoexec.bat")
o File f = new File("/autoexec.bat");
o FileInputStream f1 = new FileInputStream(f);
File Output Stream
 FileOutputStream creates an OutputStream that
you can use to write bytes to a file.
 Constructors:
 FileOutputStream(String filePath)
 FileOutputStream(File fileObj)
 FileOutputStream(String filePath, boolean append)
 FileOutputStream(File fileObj, boolean append)
EXAMPLE
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(“file1.txt");
out = new FileOutputStream(“file2.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
}
finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close(); }
}
DataOutput and DataInput
 Data streams support binary I/O of primitive data type values (boolean,
char, byte, short, int, long, float, and double) as well as String values.
 DataOutput defines methods that convert values of a primitive type into a
byte sequence and then writes it to the underlying stream.
 Constructor
o DataInputStream dis = new DataInputStream (new FileInputStream
("data.txt"));
o DataOutputStream dos = new DataOutputStream (new FileOutputStream
("output.dat"));
 DataInputStream is the complement of DataOuputStream and the
methods are also equivalent such as readDouble()
EXAMPLES
package chapter2;
import java.io.*;
public class file2 {
public static void main(String args[]) throws FileNotFoundException, IOException{
//First, write the data
DataOutputStream dout =new DataOutputStream(new FileOutputStream("Test.dat"));
try {
dout.writeDouble(199.6);
dout.writeChar('v');
dout.writeInt(1000);
dout.writeBoolean(true);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open Output File");
return;
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}}}
package chapter2;
import java.io.*;
public class file3 {
public static void main(String args[]) throws FileNotFoundException, IOException{
// Now, read the data back.
DataInputStream din =new DataInputStream(new FileInputStream("Test.dat"));
try{
double d = din.readDouble();
char c= din.readChar();
int i = din.readInt();
boolean b = din.readBoolean();
System.out.println("Here are the values: " +
d + " " + i + " " + b+ " " + c);
}
catch(FileNotFoundException e) {
System.out.println("Cannot Open Input File");
return;
} catch(IOException e) {
System.out.println("I/O Error: " + e);
} } }
Exceptions in IO
File Reader and File Writer
 The FileReader class creates a Reader that you can use to
read the contents of a file.
 Reading from file
o FileReader(String filePath)
o FileReader(File fileObj)
 Writing to File
o FileWriter(String fileName)
o FileWriter(String fileName, boolean append)
 If append is true, then the file is appended not overwritten
EXAMPLE
FileReader in= null;
FileWriter out= null;
try {
in= new FileReader(“file1.txt");
outputStream = new FileWriter(“file2.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
out.FileWriter("hello" , file.txt);
in.FileReader(file.txt, out);}
}
finally {
if (in != null) {
in.close(); }

if (out != null) {
out.close(); }
}
Buffered Reader and Writer
BufferedReader in= null;
PrintWriter out= null;
try {
in= new BufferedReader(new FileReader("xanadu.txt"));
out = new PrintWriter(new FileWriter("characteroutput.txt"));
String b;
while ((b = in.readLine()) != null) {
out.println(l); } }
finally {
if (in!= null) {
in.close(); }
if (out!= null) {
out m.close(); } }
File (java.io.File)
 Most of the classes defined by java.io operate on streams, the
File class does not.
 File deals directly with files and the file system. That is, the
File class does not specify how information is retrieved from
or stored in files; it describes the properties of a file itself.
 File object is used to obtain or manipulate the information
associated with a disk file, such as the permissions, time, date,
and directory path, and to navigate subdirectory hierarchies.
 We should use standard stream input/output classes to direct
access for reading and writing file data
Other Operations on Java Files
 Constructor
 File(String directoryPath)
 File(String directoryPath, String filename)
 To Get Paths
 getAbsolutePath(), getPath(), getParent(),
getCanonicalPath()
 To Check Files
 isFile(), isDirectory(), exists()
 To Get File Properties
 getName(), length(), isAbsolute(), lastModified(), isHidden()
//length in bytes
Cont…..
 To Get File Permissions
 canRead(), can Write(), canExecute()
 To Know Storage information
 getFreeSpace(), getUsableSpace(), getTotalSpace()
 Utility Functions
 Boolean createNewFile()
 Boolean renameTo(File nf); renames the file and returns true if
success
 Boolean delete(); deletes the file represented by path of file
(also delete directory if its empty)
 Boolean setLastModified(long ms) sets timestamp(Jan 1, 1970 UTC as a
start time)
 Boolean setReadOnly() to mark file as readable (also can be
done writable, and executable.)

You might also like