CS代写 CS 213 SOFTWARE METHODOLOGY

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 PowCoder代写 加微信 powcoder

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:\book\welcome.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(\n)
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 it’s 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,theresource’sclose()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

Example—FileReader 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
DataOutputStreamconvertsprimitive- type values or strings into bytes and outputs the bytes to the stream.
Enableyoutowriteprimitivedata-type values and strings into an output stream.

Buffered Streams
• UnbufferedI/O—thismeanseachreadorwriterequest is handled directly by the OS (Operating System)
• Lessefficient,sinceeachsuchrequestoften triggers disk access, network activity, or some other operation that is relatively expensive
• BufferedI/Ostreams—read/writedatafromamemory
area known as a
• Thenativeinput/outputAPIiscalledonlywhen the buffer is empty/full
• Fourbufferedstreamclasses
Byte Streams—BufferedInputStream,
BufferedOutputStream
Character Streams—BufferedReader, BufferedWriter

BUFFERED SRTREAMS
• BufferedInputStream/BufferedOutputStream can be used to speed up input and output by reducing the number of disk reads and writes.
• Using BufferedInputStream, the whole block of data on the disk is read into the buffer in the memory at a time
• The individual data are then loaded to your program from the buffer
• Using BufferedOutputStream, the individual data are first written to the buffer in the memory. When the buffer is full, all data in the buffer are written to the disk at a time

BufferedInputStream/BufferedOutputStream does not contain new methods; they inherit the methods from the InputStream/OutputStream classes.
It manages a buffer behind the scene and automatically reads/writes data from/to disk on demand.
You can wrap a BufferedInputStream/BufferedOutputStream on any InputStream/ OutputStream using the constructors
inStream = new BufferedReader(new FileReader(“myinput.dat”)); outStream = new BufferedWriter(new FileWriter(“myoutput.dat”));

Flushing Buffered Streams
Write out a buffer at critical points, without waiting for it to fill (full)
Some buffered output classes support autoflush, specified by an optional constructor argument
For example, an
autoflush PrintWriter object flushes the buffer on every invocation of println() or format()
flush() method is valid on any output stream, but has no effect unless the stream is buffered
You should always use buffered I/O to speed up input and output.
For small files, you may not notice performance improvements. However, for large files—over 100 MB—you will see substantial improvements using buffered I/O.

Example – copying files
File sourceFile = newFile(args[0]); //getting the source file name from command line if (!sourceFile.exists()) {
System.out.println(“Source file ” + args[0] + ” does not exist”);
System.exit(2); }
File targetFile = newFile(args[1]); //getting the destination file name from command line if (targetFile.exists()) {
System.out.println(“Target file ” + args[1] + ” already exists”);
System.exit(3); }
try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile));)
int r, numberOfBytesCopied = 0;
while ((r = input.read()) != −1) { //while not EOF, keep copying the bytes output.write((byte)r);
numberOfBytesCopied++;
System.out.println(numberOfBytesCopied + ” bytes copied”); }

Object I/O
• ObjectInputStream/ObjectOutputS tream classes can be used to read/write serializable objects.
• ObjectInputStream/ObjectOutputS tream enables you to perform I/O for objects in addition to primitive- type values and strings.
• Since ObjectInputStream/ ObjectOutputStream contains all the functions of DataInputStream/DataOutputStrea m, you can replace DataInputStream/DataOutputStrea m completely with ObjectInput Stream/ObjectOutputStream.

Object I/O – example
try (ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream(“object.dat”)); ) {
output.writeUTF(“John”);
output.writeDouble(85.5);
output.writeObject(new java.util.Date());
String name = input.readUTF();
double score = input.readDouble();
Date date = (Date)(input.readObject());

The Serializable Interface
• Not every object can be written to an output stream. Objects that can be written are said to be serializable.
• A serializable object is an instance of the java.io.Serializable interface, so the object’s class must implement Serializable.
• The Serializable interface is a marker interface. Since it has no methods, you don’t need to add additional code in your class that implements Serializable.
• Implementing this interface enables the Java serialization mechanism to automate the process of storing objects and arrays.

Serialization
• To appreciate this automation feature, consider what you otherwise need to do in order to store an object.
• Suppose that you wish to store an ArrayList object. To do this, you need to store all the elements in the list. Each element is an object that may contain other objects. As you can see, this would be a very tedious process.
• Java provides a built-in mechanism to automate the process of writing objects. This process is referred as object serialization, which is implemented in ObjectOutputStream.
• In contrast, the process of reading objects is referred as object deserialization, which is implemented in ObjectInputStream.

Serialization
• ManyclassesintheJavaAPIimplementSerializable.
• Allthewrapperclassesforprimitive-typevalues
implement java.io.Serializable.
• Attemptingtostoreanobjectthatdoesnotsupport the Serializable interface would cause a NotSerializableException.
• Whenaserializableobjectisstored,theclassofthe object is encoded; this includes the class name and the signature of the class, the values of the object’s instance variables, and the closure of any other objects referenced by the object.
• Thevaluesoftheobject’sstaticvariablesare not stored.

The transient Keyword
If an object is an instance of Serializable but contains nonserializable instance data fields, can it be serialized?
• TheanswerisNO.
To enable the object to be serialized, mark these data fields with the transient keyword to tell the JVM to ignore them when writing the object to an object stream
public class C implements java.io.Serializable { private int v1;
private static double v2; //not serialized
private transient A v3 = new A(); //not serialized

Serialization
If an object is written to an object stream more than once, will it be stored in multiple copies? No, it will not.
When an object is written for the first time, a serial number is created for it.
The JVM writes the complete contents of the object along with the serial number into the object stream.
After the first time, only the serial number is stored if the same object is written again.
When the objects are read back, their references are the same since only one object is actually created in the memory.

Serializing arrays
• An array is serializable if all its elements are serializable.
• An entire array can be saved into a file using writeObject and later can be restored using readObject.
int[] numbers = {1, 2, 3, 4, 5};
String[] strings = {“John”, “Susan”, “Kim”};
try ( ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream(“array.dat”,true)); ) { output.writeObject(numbers);
output.writeObject(strings);
int[] newNumbers = (int[])(input.readObject()); String[] newStrings = (String[])(input.readObject());

• Java provides the RandomAccessFile class to allow dat

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com