Uploaded by parthmaheshwari943

12-Java I O streams, FileInputStream & FileOutputStream , File Reader & File Writer-04-11-2023

advertisement
MODULE-6
IO Stream and Files
Dr. S. Vinila Jinny, ASP/SCOPE, VIT, Vellore.
http://www.free-powerpoint-templates-design.com
Syllabus
Java I/O streams – FileInputStrea
m & FileOutputStream – File Read
er & File Writer – DataInputStream
& DataOutputStream – BufferedInp
utStream & Buffered Output Strea
m – PrintOutPutStream – Serializat
ion and Deserialization.
Java I/O
Streams
• Java I/O (Input and Output) is
used to process the input and
produce the output.
• Stream is a logical connection
between the JAVA Program and
devices through which we transfer
the data for storing and reading
.
Java I/O
Streams
• Java treats the flow of data as Stream
• Java Stream classified as Input
Stream and Output Stream.
• java.io package contains a large
number of classes to support streams
standard
or
default
streams
h
Standard Streams
• System.in: This is the standard input stream that is
used to read characters from the keyboard or any other
standard input device.
• System.out: This is the standard output stream that is
used to produce the result of a program on an output
device like the computer screen.
• System.err: This is the standard error stream that is
used to output all the error data that a program might
throw, on a computer screen or any standard output
device.
Types of Streams:
• Depending on the type of operations, streams can be
divided into two primary classes:
• Input Stream
• Output Stream
• Depending on the types of file, Streams can be divided
into two primary classes:
• Byte Stream
• Character Stream
import java.io.*;
public class BStream
{
public static void main( String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
try {
sourceStream = new FileInputStream("sorcefile.txt");
targetStream= new FileOutputStream("targetfile.txt");
int temp;
while (( temp = sourceStream.read())!= -1)
targetStream.write((byte)temp);
}
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}
import java.io.*;
public class GfG {
public static void main(
String[] args) throws IOException
{
FileReader sourceStream = null;
try {
sourceStream = new FileReader("test.txt");
int temp;
while (( temp = sourceStream.read()) != -1)
System.out.println((char)temp);
}
finally {
if (sourceStream != null)
sourceStream.close();
}
}
}
Java File IO List files and directories
File class under java.io package
Create a new File object:
File dir = new File(“C:/Path/To/My/Directory”);
Use one of the following methods of the File class:
String[] list()
String[] list(FilenameFilter filter)
File[] listFiles()
File[] listFiles(FileFilter filter)
File[] list(FilenameFilter filter)
Java File IO List files and directories
•
The list() methods return an array of Strings.
•
The listFiles() methods return an array of File objects.
•
The non-argument methods list everything under the directory.
•
The argument-based methods list only files and directories which
satisfy the filter we provided.
Java File IO List files and directories
Directory Listing Code
1String dirPath = "g:/Music/English";
2File dir = new File(dirPath);
3String[] files = dir.list();
4if (files.length == 0) {
5
System.out.println("The directory is empty");
6} else {
7
for (String aFile : files) {
8
System.out.println(aFile);
9
}
10}
Reader, InputStreamReader, FileReader
and BufferedReader
Reader is the abstract class for reading character streams.
It implements the following fundamental methods:
• read(): reads a single character.
• read(char[]): reads an array of characters.
• skip(long): skips some characters.
• close(): closes the stream.
InputStreamReader
• InputStreamReader is a bridge from byte streams to
character streams.
• It converts bytes into characters using a specified
charset.
• The charset can be default character encoding of the
operating system, or can be specified explicitly when
creating an InputStreamReader.
FileReader and BufferedReader
• FileReader is a convenient class for reading text files using the
default character encoding of the operating system.
• BufferedReader reads text from a character stream with efficiency
(characters are buffered to avoid frequently reading from the
underlying stream) and provides a convenient method for reading a
line of text readLine().
Reader classes of java.io Package
Writer, OutputStreamWriter, FileWriter
and BufferedWriter
Writer is the abstract class for writing character streams.
It implements the following fundamental methods:
• write(int): writes a single character.
• write(char[]): writes an array of characters.
• write(String): writes a string.
• close(): closes the stream.
OutputStreamReader
• OutputStreamWriter is a bridge from byte streams to
character streams.
• Characters are encoded into bytes using a specified
charset.
• The charset can be default character encoding of the
operating system, or can be specified explicitly when
creating an OutputStreamWriter.
FileWriter and BufferedWriter
FileWriter is a convenient class for writing text files using the default
character encoding of the operating system.
BufferedWriter writes text to a character stream with efficiency
(characters, arrays and strings are buffered to avoid frequently writing
to the underlying stream) and provides a convenient method for
writing a line separator: newLine().
Writer classes of java.io Package
Character Encoding and Charset
When constructing a reader or writer object, the default character encoding of
the operating system is used (e.g. Cp1252 on Windows):
1FileReader reader = new FileReader("MyFile.txt");
2FileWriter writer = new FileWriter("YourFile.txt");
For specific charset, use an InputStreamReader or OutputStreamWriter
1InputStreamReader reader = new InputStreamReader(
2
new FileInputStream("MyFile.txt"), "UTF-16");
creates a new reader with the Unicode character encoding UTF-16.
1OutputStreamWriter writer = new OutputStreamWriter(
2
new FileOutputStream("YourFile.txt"), "UTF-8");
Character Encoding and Charset
For using BufferedReader, just wrap the InputStreamReader inside
1 InputStreamReader reader = new InputStreamReader(
2
new FileInputStream("MyFile.txt"), "UTF-16");
3
4 BufferedReader bufReader = new BufferedReader(reader);
For a BufferedWriter
1 OutputStreamWriter writer = new OutputStreamWriter(
2
new FileOutputStream("YourFile.txt"), "UTF-8");
3
4 BufferedWriter bufWriter = new BufferedWriter(writer);
1package net.codejava.io;
Java Reading from Text File Example
2
3import java.io.FileReader;
4import java.io.IOException;
5
6/**
7 * This program demonstrates how to read characters from a text file.
8 * @author vinila
9 *
10 */
11public class TextFileReadingExample1 {
12
13
public static void main(String[] args) {
14
try {
15
FileReader reader = new FileReader("MyFile.txt");
16
int character;
17
18
while ((character = reader.read()) != -1) {
19
System.out.print((char) character);
20
}
21
reader.close();
22
23
} catch (IOException e) {
24
e.printStackTrace();
25
}
26
}
27
1
Java Writing to Text File Example
2
3import java.io.FileWriter;
4import java.io.IOException;
5
6/**
7 * This program demonstrates how to write characters to a text file.
8 * @author Suvilin
9 *
10 */
11public class TextFileWritingExample1 {
12
13
public static void main(String[] args) {
14
try {
15
FileWriter writer = new FileWriter("MyFile.txt", true);
16
writer.write("Hello World");
17
writer.write("\r\n");
// write new line
18
writer.write("Good Bye!");
19
writer.close();
20
} catch (IOException e) {
21
e.printStackTrace();
22
}
23
24
}
25
26}
Download