CS 213 SOFTWARE METHODOLOGY
LILY CHANG ASSOCIATE TEACHING PROFESSOR DEPARTMENT OF COMPUTER SCIENCE RUTGERS UNIVERSITY NEW BRUNSWICK FALL 2021
Java I/O Streams
Copyright By Assignmentchef assignmentchef
Data in main memory vs. Persistent data
Datayouprocesswithyourprogramssofarare temporary data in main memory
Youwillnothavethereferencetothosedata after your program terminates
Topermanentlystorethedatacreatedina program, you need to save them in a file on a disk or other permanent storage device.
Thedatainfilescanbereferencedatalater time when you run your programs again, or they can be referenced by other programs
Absolute file name
Every file is placed in a directory in the file system.
An absolute file name (or full name) contains a file name with its complete path and drive letter.
For example, c:bookwelcome.java is the absolute file name for the file Welcome.java on the Windows operating system; for UNIX based operating system, it could be /home/username/Documents/- welcome.java, where /home/username/Documents referred to as the directory name
Relative file name
Is in relation to the current working directory; that is, the complete directory path for a relative file name is omitted.
File Names
The filename is a string
The File class is a wrapper class for the file
name and its directory path.
The File class contains the methods for obtaining file and directory properties, and for renaming and deleting files and directories, however, the File class does not contain the methods for reading and writing file contents.
The File class in 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 in java
The directory separator for Windows is a backslash (); the backslash is a special character in Java and should be written as \ in a string literal
Do not use absolute file names in your program. If you use a file name such as c:\book\Welcome.java, it will work on
Windows but not on other platforms. You should use a file name relative to the current directory.
The forward slash (/) is the Java directory separator, which is the same as on UNIX
For example, the statement new File(image/us.gif) works on Windows, UNIX, and any other platform.
Constructing a File instance does not create a file on the machine.
You can create a File instance for any file name regardless of
whether it exists or not.
You can invoke the exists() method on a File instance to check whether the file exists; so the exception at runtime can be properly handled.
The File class path name
By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir and is typically the directory in which the Java virtual machine was invoked.
The parent of an abstract pathname may be obtained by invoking the getParent() method of this instance
Some Examples
public class TestFileClass {
public static void main(String[] args) {
java.io.File file = new java.io.File(image/us.gif); System.out.println(Does it exist? + file.exists()); System.out.println(The file has + file.length() + bytes); System.out.println(Can it be read? + file.canRead()); System.out.println(Can it be written? + file.canWrite()); System.out.println(Is it a directory? + file.isDirectory()); System.out.println(Is it a file? + file.isFile()); System.out.println(Is it absolute? + file.isAbsolute()); System.out.println(Is it hidden? + file.isHidden()); System.out.println(Absolute path is + file.getAbsolutePath()); System.out.println(Last modified on +
new java.util.Date(file.lastModified()));
Java Input and Output (I/O) classes
A File object encapsulates the properties of a file or a path, but it does not contain the methods for writing/reading data to/from a file (referred to as data input and output, or I/O for short).
In order to perform I/O, you need to create objects using appropriate Java I/O classes There are two types of files: text and binary
Text I/O Scanner class (read)
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, i.e., space, tab (t) or new line(
)
The resulting tokens may then be converted into values of different types using the various next methods.
For example, the following code allows a user to read a number from System.in
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
A scanning operation may block waiting for input.
The next() and hasNext() methods and their companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token.
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method
A Scanner is not safe for multithreaded use without external synchronization.
Text I/O Scanner class
Text I/O PrintWriter class (write)
Printsformattedrepresentationsofobjectstoatext- output stream.
Thisclassimplementsalltheprintmethodsfoundin PrintStream class.
Itdoesnotcontainmethodsforwritingrawbytes,for which a program should use unencoded byte streams.
UnlikethePrintStreamclass,ifautomaticflushingis enabled, it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.
MethodsinthisclassneverthrowI/Oexceptions, although some of its constructors may; the client may inquire as to whether any errors have occurred by invoking checkError().
Example PrintWriter
File file = new File(scores.txt); if (file.exist()) {
System.out.println(File already exists.);
System.exit(1); }
PrintWriter pw = new PrintWriter(file); pw.print(); //write to file scores.txt pw.println(90);
pw.print();
pw.println(85);
pw.close();
create a new file if the file does not exist.
If the file already exists, the current content in the file will be overwritten without verifying with the user.
Binary I/O
Filescanbeclassifiedaseithertextorbinary.
Afilethatcanbeprocessed(read,created,or modified) using a text editor such as Notepad on Windows or vi on UNIX is called a text file.
Allotherfilesarecalledbinaryfiles.
Youcannotreadbinaryfilesusingatext-
Binaryfilesareapplicationspecific;theyare designed to be read by application programs
Forexample,aMicrosoftWorddocument can be processed by MS Word application; Java .class files are processed by the Java JVM
Java I/O classes
TherearemanyI/Oclassesforvariouspurposes.In general, these can be classified as input classes and output classes.
Aninputclasscontainsthemethodstoreaddata, and an output class contains the methods to write data.
PrintWriterisanexampleofanoutputclass,and Scanner is an example of an input class.
Computersdonotdifferentiatebetweenbinaryfiles and text files. All files are stored in binary format, and thus all files are essentially binary files.
TextI/OisbuiltuponbinaryI/Otoprovidealevelof abstraction for character encoding and decoding,
Java I/O classes
Encoding and decoding are automatically performed for text I/O. The JVM converts Unicode to a file-specific encoding when writing a character and converts a file-specific encoding to Unicode when reading a character.
Binary I/O does not require conversions. If you write a numeric value to a file using binary I/O,
the exact value in the memory is copied into the file.
Java I/O classes
In general, you should use text input to read a file created by a text editor or a text output program and use binary input to read a file created by a Java binary output program.
Binary I/O is more efficient than text I/O because binary I/O does not require encoding and decoding.
Java Binary I/O classes
I/O Streams, a powerful concept that greatly simplifies I/O operations
Byte Streams handle I/O of
Character Streams handle I/O of
automatically handling translation to and from the local character set
Buffered Streams optimize input and output by reducing the number of calls to the native API.
Scanning and Formatting allows a program to read and write formatted text
I/O from the Command Line
Data Streams handle binary I/O of primitive data type
and String values
Object Streams handle binary I/O of objects
raw binary data.
character data,
Java I/O Streams
A stream is a sequence of data
I/O Stream represents an input source or an output destination
A stream can represent many kinds of sources and destinations, including disk files, devices, other programs, and memory arrays
Streams support many kinds of data, including simple bytes, primitive data types, localized characters, and objects
I/O Stream
A program uses an input stream to read data from a source, and uses
an output stream to write data to a destination, one item at time input stream
output stream
Byte Stream
Perform input and output of 8-bit bytes (low-level I/O)
All byte stream classes are descended from InputStream and OutputStream, for example
File I/O byte streams FileInputStream and FileOutputStream
import java.io.*;
FileInputStream in = null; FileOutputStream out = null;
in = new FileInputStream(myin.dat); out = new FileOutputStream(myout.dat); int c;
while ((c = in.read()) != -1)
out.write(c);
catch (..)
finally
Closing I/O Streams
Closing a stream when its no longer needed is very important Avoid serious resource leaks!
try { }
Catch ( ) { }
if (in != null)
in.close();
if (out != null)
out.close();
Try-with-Resources
try ( BufferedReader br = new BufferedReader(new FileReader(path)); )
return br.readLine();
Aresourceisdeclaredandcreatedfollowedbythekeywordtryintheparentheses;theresourcesmustbeasubtypeof- AutoCloseable
Multipleresourcescanbedeclaredandcreatedinsidetheparentheses.
Aftertheblockisfinished,theresourcesclose()methodisautomaticallyinvokedtoclosetheresource.
Interfacejava.lang.AutoCloseableandjava.io.closeable
BufferedReaderbrwillbeclosedregardlessofwhetherthetrystatementcompletesnormallyorabruptly
Character Streams
Java platform stores character values using Unicode conventions
Character stream I/O automatically translates this internal format to and from the local character set
Ready for internationalization
All character stream classes are descended from Reader and Writer
For example, FileReader and FileWriter
ExampleFileReader and FileWriter
import java.io.*;
FileReader inputStream = null;
FileWriter outputStream = null;
inputStream = new FileReader(mycharIn.dat); outputStream = new FileWriter(mycharOutt.txt); int c;
while ((c = inputStream.read()) != -1)
outputStream.write(c);
catch ( )
finally { }
Character Streams
Character streams are often wrappers for byte streams
The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes
Filter Streams
Filterstreamsarestreamsthatfilterbytesforsome purpose.
Thebasicbyteinputstreamprovidesareadmethod that can be used only for reading bytes.
Ifyouwanttoreadintegers,doubles,orstrings,you need a filter class to wrap the byte input stream.
Usingafilterclassenablesyoutoreadintegers, doubles, and strings instead of bytes and characters.
FilterInputStreamandFilterOutputStreamarethe base classes for filtering data.
Whenyouneedtoprocessprimitivenumeric types, use DataInputStream and DataOutputStream to filter bytes.
DATAINPUTSTREAM CLASS
DataInputStream reads bytes from the stream and converts them into appropriate primitive-type values or strings.
Filter an input stream of bytes into primitive data-type values and strings.
DATAOUTPUTSTREAM CLASS