0% found this document useful (0 votes)
23 views54 pages

Chapter 2

Uploaded by

shadowalker2276
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)
23 views54 pages

Chapter 2

Uploaded by

shadowalker2276
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/ 54

Chapter Two

Streams and File I/O

Course Title:- Advanced


Programming
Instructor:- Feyisa K.
Email:- [email protected]
Outlines
1.1. Java Files
 Create a File
 Write a File
 Read Files
 Delete Files
1.2.Java Directories
1.3 Java I/O Stream
Java Files
 Java File class represents the files and directory pathnames
in an abstract manner.
 This class is used for creation of files and directories, file
searching, file deletion, etc.
 The File object represents the actual file/directory on the
disk.
File Class Constructors
 Following is the list of constructors to create a File object.
Java Files cont…
File Class Methods
 Once you have File object in hand, then there is a list of helper
methods which can be used to manipulate the files.
Java Files cont…
Java Files cont…
Java Files….cont
Java Files….cont
File Class Example in Java
 Following is an example to demonstrate File object −
import java.io.File;

public class FileDemo {

public static void main(String[] args) {


File f = null;
String[] strs = {"test1.txt", "test2.txt"};
try {
// for each string in string array
for(String s:strs ) {
// create new file
f = new File(s);

// true if the file is executable


boolean bool = f.canExecute();
Java Files….cont
// find the absolute path
String a = f.getAbsolutePath();

// prints absolute path


System.out.print(a);

// prints
System.out.println(" is executable: "+
bool);
}
} catch (Exception e) {
// if any I/O error occurs
e.printStackTrace();
}
}
}
Java Files….cont
 Consider there is an executable file test1.txt and
another file test2.txt is non executable in the
current directory. Let us compile and run the
above program, This will produce the following
result −
Output
/home/cg/root/2880380/test1.txt is executable: false
/home/cg/root/2880380/test2.txt is executable: false
Create File in Java
 We can create a file in Java using multiple ways. Following are
three most popular ways to create a file in Java −
 Using FileOutputStream() constructor
 Using File.createNewFile() method
 Using Files.write() method
 Let's take a look at each of the way to create file in Java.
Create File Using FileOutputStream Constructor
 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.
 Here are two constructors which can be used to create a
FileOutputStream object.
 Following constructor takes a file name as a string to create an
input stream object to write the file
 Syntax
OutputStream f = new FileOutputStream("C:/java/hello.txt")
First, we create a file object using File() method as follows −
File f = new File("C:/java/hello.txt");
OutputStream f = new FileOutputStream(f);
Create File in Java…cont
Example: Create File Using FileOutputStream Constructor
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileTest {

public static void main(String args[]) {

try {
byte bWrite [] = {65, 66, 67, 68, 69};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets the position of the awt button.
Output:

Create File in Java…cont

InputStream is = new FileInputStream("test.txt");


int size = is.available();

for(int i = 0; i < size; i++) {


System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given
numbers in binary format. Same would be the output on the
stdout screen.
Output
A B C D E
Create File in Java…cont
Create File Using File.createNewFile() Method
 File.createNewFile() method allows to create a file
in given location or in current directory as follows

 Syntax
File file = new File("d://test//testFile1.txt");
//Create the file
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
Create File in Java…cont
Example: Create File Using File.createNewFile() Method
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest {
public static void main(String args[]) {
try {
File file = new File("d://test//testFile1.txt");
//Create the file
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
Create File in Java…cont
// Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
// read content
FileReader reader = new FileReader(file);

int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
System.out.print(ch);
}
} catch (IOException e) {
System.out.print("Exception");
}
}
}

Output
The above code would create file test.txt and would write given string
in text format. Same would be the output on the stdout screen.
File is created!
Test data
Create File in Java…cont
Create File Using Files.write() Method
 Files.write() is a newer and more flexible method
create a file and write content to a file in same
command as shown below −
 Syntax
String data = "Test data";
Files.write(Paths.get("d://test/testFile3.txt"),
data.getBytes());
List<String> lines = Arrays.asList("1st line", "2nd line");
Files.write(Paths.get("file6.txt"), lines,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Create File in Java…cont
Example: Create File Using Files.write() Method
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

public class FileTest {

public static void main(String args[]) {

try {
String data = "Test data";
Files.write(Paths.get("d://test/testFile3.txt"),
data.getBytes());
List<String> lines = Arrays.asList("1st line", "2nd
line");
Create File in Java…cont
Files.write(Paths.get(
"file6.txt"), lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
List<String> content =
Files.readAllLines(Paths.get("d://test/testFile3.txt"));
System.out.println(content);
content =
Files.readAllLines(Paths.get("file6.txt"));
System.out.println(content);
} catch (IOException e) {
System.out.print("Exception");
}
}
}

Output
 The above code would create file test.txt and would write
given strings in text format. Same would be the output on
the stdout screen.
[Test data]
[1st line, 2nd line]
Write To File in Java…cont
 We can write to a file in Java using multiple ways. Following are three most
popular ways to create a file in Java
Using FileOutputStream() constructor
Using FileWriter.write() method
Using Files.write() method
Write To File Using FileOutputStream Constructor
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.
Here are two constructors which can be used to create a FileOutputStream
object.
Syntax
Following constructor takes a file name as a string to create an input stream
object to write the file
OutputStream f = new FileOutputStream("C:/java/hello.txt")
Following constructor takes a file object to create an output stream object to
write the file. First, we create a file object using File() method then we're
writing bytes to the stream as follows
File f = new File("C:/java/hello.txt");
OutputStream f = new FileOutputStream(f);
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
Write To File in Java…cont
 Example: Write To File Using FileOutputStream
Constructor
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileTest {

public static void main(String args[]) {

try {
byte bWrite [] = {65, 66, 67, 68, 69};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
Write To File in Java…cont
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i = 0; i < size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers
in binary format. Same would be the output on the stdout screen.
Output
A B C D E
Write To File in Java…cont
Write To File Using FileWriter.write() Method
 FileWriter.write() method of FileWriter class allows to
write chars to a file as shown below
Syntax
// get an existing file
File file = new File("d://test//testFile1.txt");
// Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
Write To File in Java…cont
Example: Write To File Using FileWriter.write()
Method
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileTest {

public static void main(String args[]) {

try {
File file = new File("d://test//testFile1.txt");

//Create the file


if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
Write To File in Java…cont
// Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
// read content
FileReader reader = new FileReader(file);
int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
System.out.print(ch);
}
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given string
in text format. Same would be the output on the stdout screen.
Output
File is created!
Test data
Write To File in Java…cont
Write To File Using Files.write() Method
Files.write() is a newer and more flexible method create
a file and write content to a file in same command as
shown below
Syntax
String data = "Test data";
Files.write(Paths.get("d://test/testFile3.txt"), data.getBytes());
List<String> lines = Arrays.asList("1st line", "2nd line");
Files.write(Paths.get("file6.txt"), lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Write To File in Java…cont
Example: Write To File Using Files.write() Method
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

public class FileTest {

public static void main(String args[]) {

try {
String data = "Test data";
Files.write(Paths.get("d://test/testFile3.txt"),
data.getBytes());
List<String> lines = Arrays.asList("1st line", "2nd line");
Files.write(Paths.get(
"file6.txt"), lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Write To File in Java…cont
List<String> content =
Files.readAllLines(Paths.get("d://test/testFile3.txt"));

System.out.println(content);

content = Files.readAllLines(Paths.get("file6.txt"));

System.out.println(content);
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given
strings in text format. Same would be the output on the stdout
screen.
Output
[Test data]
[1st line, 2nd line]
Reading a File in Java
 We can read a file in Java using multiple ways. Following are three
most popular ways to create a file in Java −
 Using FileInputStream() constructor
 Using FileReader.read() method
 Using Files.readAllLines() method

Reading File Using FileInputStream() Constructor


 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.
Syntax
 Following constructor takes a file name as a string to
create an input stream object to read the file
InputStream f = new FileInputStream("C:/java/hello.txt");
 Following constructor takes a file object to create an input
stream object to read the file. First we create a file object using
File() method as follows
File f = new File("C:/java/hello.txt");
InputStream f = new FileInputStream(f);
Reading a File in Java … Cont

 Example: Reading File Using


FileInputStream() Constructor
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileTest {
public static void main(String args[]) {
try {
byte bWrite [] = {65, 66, 67, 68, 69};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
Reading a File in Java … Cont
os.close();

InputStream is = new FileInputStream("test.txt");

int size = is.available();

for(int i = 0; i < size; i++) {

System.out.print((char)is.read() + " ");

is.close();

} catch (IOException e) {

System.out.print("Exception");

The above code would create file test.txt and would write given numbers in
binary format. Same would be read using FileInputStream and the output is
printed on the stdout screen.

Output

A B C D E
Reading a File in Java … Cont
Reading File Using FileReader.read() Method
 FileReader.read() method of FileReader class allows to read
chars from a file as shown below −
Syntax
// get an existing file
File file = new File("d://test//testFile1.txt");
// read content
FileReader reader = new FileReader(file);
int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
System.out.print(ch);
}
Reading a File in Java … Cont
Example: Reading File Using FileReader.read() Method
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileTest {


public static void main(String args[]) {
try {
File file = new File("d://test//testFile1.txt");

//Create the file


if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}

// Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
Reading a File in Java … Cont
// read content
FileReader reader = new FileReader(file);
int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
System.out.print(ch);
}
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given string
in text format. Same would be the output on the stdout screen.
Output
File is created!
Test data
Reading a File in Java … Cont
Reading File Using Files.readAllLines() Method
 Files.readAllLines() is a newer method to read all content of a file as a List of String as
shown below −
 Syntax
List<String> content = Files.readAllLines(Paths.get("d://test/testFile3.txt"));

Example: Reading File Using Files.readAllLines()


Method
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
public class FileTest {
public static void main(String args[]) {
try {
String data = "Test data";
Reading a File in Java … Cont
Files.write(Paths.get("d://test/testFile3.txt"), data.getBytes());
List<String> lines = Arrays.asList("1st line", "2nd line");
Files.write(Paths.get(
"file6.txt"), lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);

List<String> content =
Files.readAllLines(Paths.get("d://test/testFile3.txt"));
System.out.println(content);
content = Files.readAllLines(Paths.get("file6.txt"));
System.out.println(content);
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given
strings in text format. Same would be the output on the stdout
screen.
Output
[Test data]
[1st line, 2nd line]
Deleting Files in Java
 To delete a file in Java, you can use the File.delete()
method. This method deletes the files or directory
from the given path.
Syntax
 Following is the syntax of deleting a file
using File.delete() method
File file = new File("C:/java/hello.txt");
if(file.exists()){
file.delete();
}
Deleting File from Current Directory
Following is the example to demonstrate File.delete() method usage to delete an
existing file in current directory−
Example
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Deleting Files in Java… Cont
public class FileTest {
public static void main(String args[]) throws IOException {
BufferedWriter out = new BufferedWriter (new FileWriter("test.txt"));
out.write("test data");
out.close();

File file = new File("test.txt");


if(file.exists()) {
boolean success = file.delete();

if (success) {
System.out.println("The file has been successfully deleted.");
}else {
System.out.println("The file deletion failed.");
}
}else {
System.out.println("The file is not present.");
}
}
}

Output
The above code would create file test.txt and would write given numbers in binary
format. Same would be the output on the stdout screen. This will produce the
following result
The file has been successfully deleted.
Directory in Java
 A directory is a File which can contain a list of other files and
directories.
 You use File object to create directories, to list down files
available in a directory.
 For complete detail, check a list of all the methods which you
can call on File object and what are related to directories.
Creating Directories
 There are two useful File utility methods, which can be used to create
directories
 The mkdir() method creates a directory, returning 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.
 The mkdirs() method creates both a directory and all the parents of
the directory.
Directory in Java…cont
Example to Create Directory in Java
 Following example creates "/tmp/user/java/bin" directory
import java.io.File;
public class DirectoryTest {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File directory = new File(dirname);
// Create directory now.
directory.mkdirs();
// create new file object
File file = new File("/tmp/user/java/bin");
System.out.println(file.exists());
}
}
Output
Compile and execute the above code to create "/tmp/user/java/bin" folders.
true
Note:- Java automatically takes care of path separators on UNIX and Windows
as per conventions. If you use a forward slash (/) on a Windows version of
Java, the path will still resolve correctly.
Directory in Java…cont
Listing (Reading) Directories
 You can use list() method provided by File object to list down
all the files and directories available in a directory as follows
Example to Read (List) a Directory in Java

import java.io.File;
public class DirectoryTest {
public static void main(String[] args) {
File file = null;
String[] paths;
try {
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
Directory in Java…cont
// for each name in the path array
for(String path:paths) {
// prints filename and directory name
System.out.println(path);
}
} catch (Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
Output
This will produce the following result based on the directories and
files available in your /tmp directory
user
Directory in Java…cont
Deleting Directories
 You can use delete() method provided by File object to delete a directory as follows
Example to Delete a Directory in Java
import java.io.File;
public class DirectoryTest {
public static void main(String[] args) {
File file = new File("/tmp/user/java/bin");
if(file.exists()) {
boolean success = file.delete();
if (success) {
System.out.println("The directory has been
successfully deleted.");
}else {
System.out.println("The directory deletion failed.");
} } else {
System.out.println("The directory is not present.");
} } }
Output
This will produce the following result based on the directories and files available
in your /tmp directory
The directory has been successfully deleted.
Stream
 A stream can be defined as a sequence of data. There are
two kinds of Streams
 InPutStream :− The InputStream is used to read data from
a source.
 OutPutStream :− The OutputStream is used for writing
data to a destination.

 Java provides strong but flexible support for I/O related to


files and networks but this tutorial covers very basic
functionality related to streams and I/O.
We will see the most commonly used examples one by one
Stream…cont
Byte Streams
 Java byte streams are used to perform input and output of 8-bit bytes.
 Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
 Following is an example which makes use of these two classes to copy
an input file into an output file
Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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 the 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 the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Stream…cont
Character Streams
 Java Byte streams are used to perform input and output of
8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode.
 Though there are many classes related to character streams
but the 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.
 We can re-write the above example, which makes the use of
these two classes to copy an input file (having unicode
characters) into an output file
Example
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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 the 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 the above code in
CopyFile.java file and do the following
$javac CopyFile.java
$java CopyFile
Standard Streams
 All the programming languages provide support for standard
I/O where the user's program can take input from a keyboard
and then produce an output on the computer screen.
 If you are aware of C or C++ programming languages, then
you must be aware of three standard devices STDIN, STDOUT
and STDERR.
 Similarly, Java provides the following three standard streams
 Standard Input :− This is used to feed the data to user's
program and usually a keyboard is used as standard input
stream and represented as System.in.
 Standard Output :− This is used to output the data produced
by the user's program and usually a computer screen is used
for standard output stream and represented as System.out.
 Standard Error :− This is used to output the error data
produced by the user's program and usually a computer screen
is used for standard error stream and represented as
System.err.
Standard Streams
import java.io.InputStreamReader;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Standard Streams
Let's keep the above code in ReadConsole.java file and try to
compile and execute it as shown in the following program. This
program continues to read and output the same character until
we press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Any Question
THANKS!!!
!!

You might also like