Java File I/O Streams

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

OutputStream object's helper methods

- can be used to write to stream or to do other operations on the stream. - public void close() throws IOException{} -protected void finalize()throws IOException {} -public void write(int w)throws IOException{} -public void write(byte[] w)

java.io package

- contains nearly every class you might ever need to perform input and output (I/O) in Java - All these streams represent an input source and an output destination - The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

FileInputStream

- is used for reading data from the files. - Objects can be created using the keyword new and there are several types of constructors available. InputStream f = new FileInputStream("C:/java/hello"); or File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f);

FileOutputStream

- is used to create a file and write data into it. - The stream would create a file, if it doesn't already exist, before opening it for output. ex1: OutputStream f = new FileOutputStream("C:/java/hello") ex2: File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(f);

Creating Directories: 2 useful File utility methods

- mkdir( ) - mkdirs()

What is the Linux, Unix or Mac separator character?

/ (forward slash)

Example Program:

1 import java.io.PrintWriter; 2 import java.io.FileOutputStream; 3 import java.io.FileNotFoundException; 4 public class TextFileOutputDemo 5 { 6 public static void main(String[] args) 7 { 8 PrintWriter outputStream = null ; 9 try 10 { 11 outputStream = 12 new PrintWriter( new FileOutputStream("stuff.txt")); 13 } 14 catch (FileNotFoundException e) 15 { 16 System.out.println("Error opening the file stuff.txt."); 17 System.exit(0); 18 } 19 System.out.println("Writing to file."); 20 outputStream.println("The quick brown fox"); 21 outputStream.println("jumps over the lazy dog."); 22 outputStream.close(); 23 System.out.println("End of program."); 24 } 25 } Sample Output Writing to file. End of program. File stuff.txt (after the program is run.) The quick brown fox jumps over the lazy dog.

What is the end of file marker on Windows

<Ctrl> z

What is the end of file marker on Linux, Unix or Mac OS

<Enter><Ctrl>d

What is a binary file

A binary file is a computer file that is not a text file; Binary files store data in the same format that is used in the computer's memory to store the values of variables. it may contain any type of data, encoded in binary form for computer storage and processing purposes. (byte based) A file that contains raw binary data is known as a binary file. The content of a binary file is not formatted as text, and not meant to be opened in a text editor. - raw binary format. For example, a value of type int is stored as the same sequence of bytes(same sequence of zeros and ones) whether it is stored in an int variable in memory or in a binary file. So, no conversion of any kind needs to be performed when you store or retrieve a value in a binary file. This is why binary files can be handled more efficiently than text files.

public File(String File_Name)

A constructor. File_Name can be either a full or a relative pathname (which includes the case of a simple filename). File_Name is referred to as the abstract path name.

What is a Character Stream

A higher level API that automatically changes data in a file to character (text) data. - perform input and output for 16-bit unicode - most frequently used classes are, FileReader and FileWriter. - Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

What is a Byte Stream

A low level API that writes data in bytes - used to perform input and output of 8-bit bytes - most frequently used classes are, FileInputStream and FileOutputStream.

What does a Stream represent

A sequence of data - a sequence of data - two kinds of Streams = InPutStream, OutPutStream

What is Serialization

Allows a program to write whole objects out to streams and read them back again.

How does Java view each file?

As a sequential stream of bytes.

Binary Files

Binary files store data in the same format that is used in the computer's memory to store the values of variables. For example, a value of type int is stored as the same sequence of bytes (same sequence of zeros and ones) whether it is stored in an int variable in memory or in a binary file. So, no conversion of any kind needs to be performed when you store or retrieve a value in a binary file. This is why binary files can be handled more efficiently than text files.

Java BufferedInputStream class constructors

BufferedInputStream(InputStream IS) - It creates the BufferedInputStream and saves it argument, the input stream IS, for later use. BufferedInputStream(InputStream IS, int size) - It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

Java BufferedOutputStream class constructors

BufferedOutputStream(OutputStream os) - It creates the new buffered output stream which is used for writing the data to the specified output stream. BufferedOutputStream(OutputStream os, int size) - It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.

What are the 5 types of streams in I/O

Byte stream Character stream Buffered Streams Object Streams Line Oriented I/O

What type of stream do the 3 standard streams provide

Byte.

How do you iterate through a directory's contents?

Create a DirectoryStream object: DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)

public boolean createNewFile()throws IOException

Creates a new empty file named by the abstract path name, provided that a file of that name does not already exist. Returns true if successful, and returns false otherwise.

The File class DOES NOT perform what operations

Data Input or Output processes

What types of data does Data Input Stream support

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

Objects that implement the interface DirectoryStream can do what?

Enables a program to iterate through the contents of a directory

You use _________ to create directories, to list down files available in a directory.

File Object

File System Operations

File System operations : - public boolean exists() True if the file exists with the given pathname public boolean canRead() True if the file is readable. Check whether the application can read the file. public boolean setReadOnly() Sets the file to be read only public boolean canWrite() True if we have permissions to write. Check whether the application can modify the file. public boolean delete() Removes the file, false if unable to delete the file or directory public boolean createNewFile() Creates a new empty file public String getAbsolutePath() Gets the full path. Return the absolute pathname in string. public String getPath() Returns the abstract path name as a string public boolean isFile() True if abstract path is a file public boolean isDirectory() True if abstract path is a folder public File[] listFiles() Array of all files/folders in the path isHidden (): - : -Check whether the file is a hidden file or not. list(): - : - Returns an array of strings naming the files and directories in the directory.

What method from File should you use to get the system's separator?

File.separator - this is safer than assigning a separator yourself.

FileOutputStream class methods

FileChannel getChannel() It is used to return the file channel object associated with the file output stream. FileDescriptor getFD() It is used to return the file descriptor associated with the stream. 1 public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. 2 protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. 3 public void write(int w)throws IOException{} This methods writes the specified byte to the output stream. 4 public void write(byte[] w) Writes w.length bytes from the mentioned byte array to the OutputStream. void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output stream. void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset off to the file output stream. void write(int b) It is used to write the specified byte to the file output stream.

What is an input stream

Input stream - reads data from a source (does not have to be a file)

What does the acronym I/O stand for?

Input/Output

Explain a SecurityException

It occurs if the user does not have permission to write data to the file.

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast. The important points about BufferedInputStream are: When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time. When a BufferedInputStream is created, an internal buffer array is created. public class BufferedInputStream extends FilterInputStream

Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way. Java application generally uses the data output stream to write data that can later be read by a data input stream. public class DataInputStream extends FilterInputStream implements DataInput

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way. Java application generally uses the data output stream to write data that can later be read by a data input stream. public class DataOutputStream extends FilterOutputStream implements DataOutput

FileInputStream Class

Java FileInputStream Class Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class. Java FileInputStream class declaration Let's see the declaration for java.io.FileInputStream class: public class FileInputStream extends InputStream

FileInputStream Class methods

Java FileInputStream class methods Method Description long skip(long x) It is used to skip over and discards x bytes of data from the input stream. FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream. FileDescriptor getFD() It is used to return the FileDescriptor object. 1 public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. 2 protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. 3 public int read(int r)throws IOException{} public int read() It is used to read the byte of data from the input stream. This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file. 4 public int read(byte[] r) throws IOException{} public int read(byte[] r, int off, int len) It is used to read up to len bytes of data from the input stream. This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned. 5 public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. Returns an int. int available() It is used to return the estimated number of bytes that can be read from the input stream.

FileOutputStream

Java FileOutputStream is an output stream used for writing data to a file. If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. FileOutputStream class declaration Let's see the declaration for Java.io.FileOutputStream class: public class FileOutputStream extends OutputStream

Java FilterInputStream Class

Java FilterInputStream class implements the InputStream. It contains different sub classes as BufferedInputStream, DataInputStream for providing additional functionality. So it is less used individually. public class FilterInputStream extends InputStream

Java FilterOutputStream Class

Java FilterOutputStream class implements the OutputStream class. It provides different sub classes such as BufferedOutputStream and DataOutputStream to provide additional functionality. So it is less used individually. public class FilterOutputStream extends OutputStream

What are the Buffered Stream APIs used to read byte streams?

Java.io.BufferedInputStream; Java.io.BufferedOutputStream;

What are the Buffered Stream APIs used to read character streams

Java.io.BufferedReader; Java.io.BufferedWriter;

What API is used with Console?

Java.io.Console;

Which APIs are used to implement Data Streams?

Java.io.DataInputStream; Java.io.DataOutputStream;

Opening a Binary File for Reading Syntax

ObjectInputStream Input_Stream_Name = new ObjectInputStream(new FileInputStream(File_Name)); The constructor for FileInputStream may throw a FileNotFoundException , which is a kind of IOException . If the FileInputStream constructor succeeds, then the constructor for ObjectInputStream may throw a different IOException . Example ObjectInputStream inputFile = new ObjectInputStream(new FileInputStream("somefile.dat"));

ObjectOutputStream syntax

ObjectOutputStream Output_Stream_Name = new ObjectOutputStream(new FileOutputStream(File_Name)); The constructor for FileOutputStream may throw a FileNotFoundException , which is a kind of IOException . If the FileOutputStream constructor succeeds, then the constructor for ObjectOutputStream may throw a different IOException . A single catch block for IOException would cover all cases.

Java - ObjectStreamClass

ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and serialVersionUID of the class.

Explain a FileNotFoundException

Occurs if the file does not exist and a new file cannot be created

What is the following sequence of operations on files

Open the file → Process the file → Close the file Text Files Operations that can be done on text files: ● Open ● Read ● Write ● Append(Add at end) ● Close

What is an output stream

Output stream - writes data to a source (does not have to be a file)

BufferedOutputStream class Syntax

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));

Data maintained in files is called what?

Persistent data

What does the FILES class do

Provides static methods for common file & directory manipulations such as copying files, creating and deleting files and directories, getting metadata about files, and more

What is an Object Stream

Reads and writes java objects to a file. Objects written to an ObjectInputStream MUST implement java.io.Serializable

public boolean renameTo(File New_Name)

Renames the file represented by the abstract path name to New_Name. Returns true if successful; otherwise returns false. New_Name can be a relative or absolute path name. This may require moving the file. Whether or not the file can be moved is system dependent.

public String getPath()

Returns the abstract path name as a String value.

public String getName()

Returns the last name in the abstract path name (that is, the simple filename). Returns the empty string if the abstract path name is the empty string.

public long length()

Returns the length in bytes of the file named by the abstract path name. If the file does not exist or the abstract path name designates a directory, then the value returned is not specified and may be anything.

public boolean isDirectory()

Returns true if a directory(folder) exists that is named by the abstract path name; otherwise returns false.

public boolean isFile()

Returns true if a file exists that is named by the abstract path name and the file is a normal file; otherwise returns false. The meaning of normal is system dependent. Any file created by a Java program is guaranteed to be normal.

public boolean setReadOnly()

Sets the file represented by the abstract path name to be read only. Returns true if successful; otherwise returns false.

How do you invoke the Console?

System.console()

What are the 3 standard streams supported by the Java Platform?

System.in System.out System.err

What are the 3 stream objects created when java opens a file?

System.in, System.out and System.err

What is the function of System.exit

Terminates an application

public boolean canRead()

Tests whether the program can read from the file. Returns true if the file named by the abstract path name exists and is readable by the program; otherwise returns false.

public boolean canWrite()

Tests whether the program can write to the file. Returns true if the file named by the abstract path name exists and is writable by the program; otherwise returns false.

public boolean exists()

Tests whether there is a file with the abstract path name.

File I/O is done with

Text Files and Binary Files ● Files that you write and read using an editor are called text files . For example, the files that contain your Java programs are text files. Text files are sometimes also called ASCII files because they contain data encoded using a scheme known as ASCII coding. ● Binary files represent data in a way that is not convenient to read with a text editor, but that can be written to and read from a program very efficiently. They are handled as sequences of binary digits.

Text Files versus Binary Files:

Text files are designed to be read by human beings, whereas binary files are designed to be read only by programs. One advantage of text files is that they are usually the same on all computers, so you can move your text files from one computer to another with few or no problems. The implementation of binary files usually differs from one computer to another, so your binary data files ordinarily must be read only on the same type of computer, and with the same programming language, as the computer that created that file. The benefit of binary files is that they are more efficient to process than text files. Unlike other programming languages, Java also gives its binary files some of the advantages of text files. In particular, Java binary files are platform independent; that is, with Java, you can move your binary files from one type of computer to another, and your Java programs will still be able to read the binary files. This combines the portability of text files with the efficiency of binary files.

File Class

The File class is like a wrapper class for filenames. The constructor for the class File takes a string as an argument and produces an object that can be thought of as the file with that name. File is in the java.io package.

Appending Data to an existing binary file

The FileOutputStream constructor takes an optional second argument, which must be a boolean value. (true/false) true: If the argument is true, the file will not be erased if it already exists and new data will be written to the end of the file. false: If the argument is false, the file will be erased if it already exists. FileOutputStream fstream = new FileOutputStream("MyInfo.dat", true); DataOutputStream outputFile = new DataOutputStream(fstream);

The File Pointer

The RandomAccessFile class treats a file as a stream of bytes. The bytes are numbered, with the first byte being byte 0. The last byte's number is one less than the number of bytes in the file. The file pointer holds the byte number of a location in the file If the file pointer refers to a byte number that is beyond the end of the file, an EOFException is thrown when a read operation is performed To move the file pointer, you use the seek method. void seek(long position)

PrintWriter class

The class PrintWriter is the preferred stream class for writing to a text file. allows you to write data to a file using the print and println methods, as you have been using to display data on the screen. However, with an object of the class PrintWriter, the output goes to a text file. PrintWriter outputFile = new PrintWriter("Names.txt"); outputFile.println("Chris"); outputFile.println("Kathryn"); outputFile.println("Jean"); outputFile.close();

Opening a Text File for Writing Output

The class PrintWriter is the preferred stream class for writing to a text file. An object of the class PrintWriter has the methods print and println , which are like the methods System.out.print and System.out.println that you can use for screen output. However, with an object of the class PrintWriter, the output goes to a text file. Import package java.io for using PrintWriter and FileOutputStream. You create a stream of the class PrintWriter and connect it to a text file for writing as follows. Syntax: PrintWriter Output_Stream_Name; Output_Stream_Name = new PrintWriter(new FileOutputStream(File_Name)); Example: PrintWriter outputStream = null; outputStream = new PrintWriter(new FileOutputStream("stuff.txt")); After this, you can use the methods println and print to write to the file. Note: When used in this way, the FileOutputStream constructor, and thus the PrintWriter constructor invocation, can throw a FileNotFoundException , which is a kind of IOException .

Explain the "flush" method

The flush method clears the buffer. It's only available on buffered output streams. Output streams connected to files are often buffered, which means that, rather than physically writing every instance of output data as soon as possible, the data is saved in a temporary location, known as a buffer; when enough data is accumulated in this temporary location, it is physically written to the file. This can add to efficiency, since physical writes to a file can be slow. The method flush causes a physical write to the file of any buffered data. The method close includes an invocation of the method flush. flush() flushes the output stream. This forces an actual physical write to the file of any data that has been buffered and not yet physically written to the file. Normally, you should not need to invoke flush. The following method calls flush before closing the file: public void flush()

File Navigation and I/O

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O. File Class FileReader Class FileWriter Class

ObjectOutputStream

These streams can automatically convert numbers and characters to bytes that can be stored in a binary file. They allow your program to be written as if the data placed in the file, or read from the file, is not just bytes but also strings or items of any of Java's primitive data types, such as int, char, and double, or even objects of classes you define. If you do not need to access your files using an editor, then the easiest and most efficient way to read data from and write data to files.

new PrintWriter(new FileOutputStream("stuff.txt"))

This produces an object of the class PrintWriter that is connected to the file stuff.txt . Note that the name of the file, in this case, stuff.txt, is given as a String value and so is given in quotes.

Reading data from a binary file

To open a binary file for input, you use the following classes: 1) FileInputStream 2) DataInputStream To open a binary file for input, you wrap a DataInputStream object around a FileInputStream object. FileInputStream fstream = new FileInputStream("MyInfo.dat"); DataInputStream inputFile = new DataInputStream(fstream); or DataInputStream inputFile = new DataInputStream(new FileInputStream("MyInfo.dat"));

Writing and Reading Strings

To write a string to a binary file you should use the DataOutputStream class's write UTF method.

Writing data to a binary file

To write data to a binary file you must create objects from the following classes: 1) FileOutputStream 2) DataOutputStream You wrap a DataOutputStream object around a FileOutputStream object to write data to a binary file. The following code shows how a file named MyInfo.dat can be opened for binary output: FileOutputStream fstream = new FileOutputStream("MyInfo.dat"); DataOutputStream outputFile = new DataOutputStream(fstream); or DataOutputStream outputFile = new DataOutputStream(new FileOutputStream("MyInfo.dat"));

public boolean delete()

Tries to delete the file or directory named by the abstract path name. A directory must be empty to be removed. Returns true if it was able to delete the file or directory. Returns false if it was unable to delete the file or directory.

The console provides what type of stream?

True character.

What does URI mean

Uniform Resource Identifier file c://c:/data.txt

What is a Buffered Stream

Used to increase performance by avoiding OS level I/O operations for each character that is read or written. They have an internal buffer that holds data that are waiting to be read or written

Example of Character Streams

We can re-write above example which makes use of these two classes to copy an input file having unicode characters into an output file: import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let's have a file input.txt with the following content: This is test for copy file. As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following: $javac CopyFile.java $java CopyFile

What is the Windows separator character?

\ (backslash)

What format do character-based streams output or input?

a sequence of characters in which every character is 2 bytes

What format do byte-based streams output or input?

binary format

InputStream object 's helper methods

can be used to read to stream or to do other operations on the stream. - public void close() throws IOException{} - protected void finalize()throws IOException {} - public int read(int r)throws IOException{} - public int read(byte[] r) throws IOException{} - public int available() throws IOException{}

What does class formatter do?

enables formatted data to be output to any text-based stream. (similar to System.out.printf)

Byte Streams : FileInputStream and FileOutputStream Example

import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let's have a file input.txt with the following content: This is test for copy file. As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following: $javac CopyFile.java $java CopyFile

How are sequential access files stored?

in order by the record-key file

Java FilterInputStream class Methods

int available() It is used to return an estimate number of bytes that can be read from the input stream. int read() It is used to read the next byte of data from the input stream. int read(byte[] b) It is used to read up to byte.length bytes of data from the input stream. long skip(long n) It is used to skip over and discards n bytes of data from the input stream. boolean markSupported() It is used to test if the input stream support mark and reset method. void mark(int readlimit) It is used to mark the current position in the input stream. void reset() It is used to reset the input stream. void close() It is used to close the input stream.

Java BufferedInputStream class methods

int available() It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream. int read() It read the next byte of data from the input stream. int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset. void close() It closes the input stream and releases any of the system resources associated with the stream. void reset() It repositions the stream at a position the mark method was last called on this input stream. void mark(int readlimit) It sees the general contract of the mark method for the input stream. long skip(long x) It skips over and discards x bytes of data from the input stream. boolean markSupported() It tests for the input stream to support the mark and reset methods.

Java DataInputStream class Methods

int read(byte[] b) It is used to read the number of bytes from the input stream. int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream. int readInt() It is used to read input bytes and return an int value. byte readByte() It is used to read and return the one input byte. char readChar() It is used to read two input bytes and returns a char value. double readDouble() It is used to read eight input bytes and returns a double value. boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero. int skipBytes(int x) It is used to skip over x bytes of data from the input stream. String readUTF() It is used to read a string that has been encoded using the UTF-8 format. void readFully(byte[] b) It is used to read bytes from the input stream and store them into the buffer array. void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.

Java DataOutputStream class methods

int size() It is used to return the number of bytes written to the data output stream. void write(int b) It is used to write the specified byte to the underlying output stream. void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream. void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value. void writeChar(int v) It is used to write char to the output stream as a 2-byte value. void writeChars(String s) It is used to write string to the output stream as a sequence of characters. void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value. void writeBytes(String s) It is used to write string to the output stream as a sequence of bytes. void writeInt(int v) It is used to write an int to the output stream void writeShort(int v) It is used to write a short to the output stream. void writeShort(int v) It is used to write a short to the output stream. void writeLong(long v) It is used to write a long to the output stream. void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in portable manner. void flush() It is used to flushes the data output stream.

What is the File I/O API

java.io.File

Which APIs does Byte Stream use for I/O?

java.io.FileInputStream; java.io.FileOutputStream;

Which APIs does Character Stream use for I/O

java.io.FileReader; java.io.FileWriter;

Which class would you use to output a sequential access file

java.io.Formatter

public boolean mkdir()

method creates a directory named by the abstract path name. Will not create parent directories. Returns true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

public boolean mkdirs()

method creates both a directory named by the abstract path name and will create all necessary but non-existent parents of the directory. Returns true if successful; otherwise returns false. Note that if it fails, then some of the parent directories may have been created.

If the console is not available what is the return value?

null

Explain a Character Stream

output and input data as a sequence of characters with every character being 2 bytes

Explain a Byte-Based Stream

output and input data in its binary format - a char is 2 bytes, an int is 4 bytes and a double is 8 bytes, etc.

list( ) method

provided by File object to list down all the files and directories

What does the File class do

provides information (metadata) about a file or directory.

Declaration for Java.io.BufferedOutputStream class:

public class BufferedOutputStream extends FilterOutputStream Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

Which Console method supports secure password entry?

readPassword();

new FileOutputStream("stuff.txt")

takes a file name as an argument and creates an anonymous object of the class FileOutputStream which is then used as an argument to a constructor for the class PrintWriter as follows: new PrintWriter(new FileOutputStream("stuff.txt")) This produces an object of the class PrintWriter that is connected to the file stuff.txt . Note that the name of the file, in this case, stuff.txt, is given as a String value and so is given in quotes.

What basic functions does class Scanner perform

used extensively to input data from keyboard. It can also read data from a file

What's probably the easiest way to write out a file?

using PrintStream Syntax: PrintStream ps = new PrintStream(fileName);

Java FilterOutputStream class Methods

void write(int b) It is used to write the specified byte to the output stream. void write(byte[] ary) It is used to write ary.length byte to the output stream. void write(byte[] b, int off, int len) It is used to write len bytes from the offset off to the output stream. void flush() It is used to flushes the output stream. void close() It is used to close the output stream.

Java BufferedOutputStream class methods

void write(int b) It writes the specified byte to the buffered output stream. void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset void flush() It flushes the buffered output stream.

The stream classes for processing binary files are:

● ObjectInputStream ● ObjectOutputStream.

Streams for console I/O:

● System.out (used in System.out.println ) is an output stream connected to the screen. ● System.in is an input stream connected to the keyboard. In Java, 3 streams are created for us automatically. All these streams are attached with the console. Let's see the code to print output and an error message to the console. 1) System.out: standard output stream - E.g. System.out.println("simple message"); 2) System.err: standard error stream - E.g. System.err.println("error message"); Let's see the code to get input from console. 3) System.in: standard input stream int i=System.in.read();//returns ASCII code of 1st character System.out.println((char)i);//will print the character These two streams are automatically available to your program.

Methods in the Class ObjectInputStream

● public ObjectInputStream(InputStream streamObject) There is no constructor that takes a file name as an argument. If you want to create a stream using a file name, use new ObjectInputStream(new FileInputStream(File_Name)) Alternatively, you can use an object of the class File in place of the File_Name, as follows: new ObjectInputStream(new FileInputStream(File_Object)) The constructor for FileInputStream may throw a FileNotFoundException, which is a kind of IOException. If the FileInputStream constructor succeeds, then the constructor for ObjectInputStream may throw a different IOException. ● public int readInt()throws IOException Reads an int value from the input stream and returns that int value. If readInt tries to read a value from the file and that value was not written using the method writeInt of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public int readShort()throws IOException Reads a short value from the input stream and returns that short value. If readShort tries to read a value from the file and that value was not written using the method writeShort of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public long readLong()throws IOException Reads a long value from the input stream and returns that long value. If readLong tries to read a value from the file and that value was not written using the method writeLong of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public double readDouble()throws IOException Reads a double value from the input stream and returns that double value. If readDouble tries to read a value from the file and that value was not written using the method writeDouble of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public float readFloat()throws IOException Reads a float value from the input stream and returns that float value. If readFloat tries to read a value from the file and that value was not written using the method writeFloat of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public char readChar()throws IOException Reads a char value from the input stream and returns that char value. If readChar tries to read a value from the file and that value was not written using the method writeChar of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public boolean readBoolean()throws IOException Reads a boolean value from the input stream and returns that boolean value. If readBoolean tries to read a value from the file and that value was not written using the method writeBoolean of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● public String readUTF()throws IOException Reads a String value from the input stream and returns that String value. If readUTF tries to read a value from the file and that value was not written using the method writeUTF of the class ObjectOutputStream (or written in some equivalent way), then problems will occur. If an attempt is made to read beyond the end of the file, an EOFException is thrown. ● Object readObject() throws ClassNotFoundException, IOException Reads an object from the input stream. The object read should have been written using writeObject of the class ObjectOutputStream. Throws a ClassNotFoundException if a serialized object cannot be found. If an attempt is made to read beyond the end of the file, an EOFException is thrown. May throw various other IOExceptions. ● public int skipBytes(int n) throws IOException Skips n bytes. ● public void close()throws IOException Closes the stream's connection to a file.

Some Methods in the Class ObjectOutputStream

● public ObjectOutputStream(OutputStream streamObject) There is no constructor that takes a filename as an argument. If you want to create a stream using a file name, use new ObjectOutputStream(new FileOutputStream(File_Name)) This creates a blank file. If there already is a file named File_Name, then the old contents of the file are lost. The constructor for FileOutputStream may throw a FileNotFoundException , which is a kind of IOException . If the FileOutputStream constructor succeeds, then the constructor for ObjectOutputStream may throw a different IOException. ● public void writeInt(int n) throws IOException Writes the int value n to the output stream. ● public void writeShort(short n) throws IOException Writes the short value n to the output stream. ● public void writeLong(long n) throws IOException Writes the long value n to the output stream. ● public void writeDouble(double x) throws IOException Writes the double value x to the output stream. ● public void writeFloat(float x) throws IOException Writes the float value x to the output stream. ● public void writeChar(int n) throws IOException Writes the char value n to the output stream. Note that it expects its argument to be an int value. However, if you simply use the char value, then Java will automatically type cast it to an int value. The following are equivalent: outputStream.writeChar((int)'A'); and outputStream.writeChar('A'); ● public void writeUTF(String aString) throws IOException Writes the String value aString to the output stream. UTF refers to a particular method of encoding the string. To read the string back from the file, you should use the method readUTF of the class ObjectInputStream . ● public void writeObject(Object anObject) throws IOException Writes its argument to the output stream. The object argument should be an object of a serializable class, a concept discussed later in the section titled "The Serializable Interface." Throws various IOExceptions. ● public void close()throws IOException Closes the stream's connection to a file. This method calls flush before closing the file. ● public void flush()throws IOException Flushes the output stream. This forces an actual physical write to the file of any data that has been buffered and not yet physically written to the file. Normally, you should not need to invoke flush.


संबंधित स्टडी सेट्स

MATCHING 1-5: PATIENT CONDITIONS AND MEDICAL SPECIALTIES

View Set

Life Insurance Chapter 4 Questions

View Set

AP Psychology - Unit 5 Multiple Choice Review

View Set

American Revolution, American Revolution

View Set

World History Ch 17, Section 3--Luther Leads the Reformation

View Set

Linux - Chapter 15 - System and User security

View Set