Contents
• File
Streams
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.
Method Type Description
File Methods
canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile(
Boolean This method creates an empty file
)
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePat
String Returns the absolute pathname of the file
h()
length() Long Returns the size of the file in bytes
Returns an array of the files in the
list() String[]
directory
mkdir() Boolean Creates a directory
File Operations in Java
1. Create a File
2. Get File Information
3. Write To a File
4. Read from a File
Create a import java.io.File;
File import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
// Creating an object of a file
File myObj = new File("D:FileHandlingNewFilef1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " +
myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} } }
Get File
information
import java.io.File; // Import the File class // Displaying whether the file is readable
or not
public class FileInformation {
System.out.println("Readable " +
public static void main(String[] args) { myObj.canRead());
// Creating an object of a file
File myObj = new File("NewFilef1.txt"); // Returning the length of the file in bytes
if (myObj.exists()) { System.out.println("File size in bytes " +
// Returning the file name myObj.length());
System.out.println("File name: " + } else {
myObj.getName()); System.out.println("The file does not
// Returning the path of the file exist.");
System.out.println("Absolute path: " + } File name: NewFilef1.txt
myObj.getAbsolutePath()); } Absolute path: D:FileHandlingNewFilef1.txt
// Displaying whether the file is writable Writable: true
}
Readable true
System.out.println("Writeable: " +
myObj.canWrite()); File size in bytes 52
Write to a File
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("D:FileHandlingNewFilef1.txt");
// Writes this content into the specified file
myWriter.write(“Java is the prominent programming language of the
millenium!");
// Closing is necessary to retrieve the resources allocated
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
Successfully wrote to the file
}
}}
Read from a File
import java.io.File; myReader.close();
// Import this class to handle errors } catch (FileNotFoundException e) {
import java.io.FileNotFoundException; System.out.println("An error
occurred.");
// Import the Scanner class to read text files
e.printStackTrace();
import java.util.Scanner;
}
public class ReadFromFile {
}
public static void main(String[] args) {
}
try {
// Creating an object of the file for
reading the data
File myObj = new
File("D:FileHandlingNewFilef1.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
Streams
Input - Output Streams
1.System.in: This is the standard
input stream that is used to read
characters from the keyboard or any
other standard input device.
print(), 2.System.out : This is
println(), the standard output stream that
printf() is used to produce the result of a
program on an output device like the
computer screen.
3.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
Example
import java.io.*;
public class SimpleIO { System.out.println("Enter characters,
"
+ " and '0' to
public static void main(String args[]) quit.");
throws IOException char c;
{ do {
c = (char)inp.read();
// InputStreamReader class to read System.out.println(c);
input
} while (c != '0');
InputStreamReader inp = null;
} H
E
}
// Storing the input in inp L
inp = new L
InputStreamReader(System.in); O
0
HELLO0
Types of Streams: Depending on
the type of operations
Input Output
Stream
These streams are used to read data that must Stream
These streams are used to write data as outputs
be taken as an input from a source array or file into an array or file or any output peripheral
or any peripheral device. device.
Types of Streams: Depending on
the type of files
ByteStream: This is used to process data
byte by byte (8 bits). Though it has many
classes, the FileInputStream and the
FileOutputStream are the most popular
ones. The FileInputStream is used to read
from the source and FileOutputStream is
used to write to the destination.
CharacterStream: In Java, characters are stored using Unicode
conventions. Character stream automatically allows us to read/write
data character by character. Though it has many classes, the
FileReader and the FileWriter are the most popular ones. FileReader
and FileWriter are character streams used to read from the source
and write to the destination respectively.
Example- ByteStream // Reading source file and writing
// Java Program illustrating the
// content to target file byte by byte
// Byte Stream to copy
int temp;
// contents of one file to another file.
while (( temp = sourceStream.read()) != -
import java.io.*; 1)
public class BStream { targetStream.write((byte)temp);
public static void main(String[] args) }
throws IOException
finally {
{
if (sourceStream != null)
FileInputStream sourceStream = null;
sourceStream.close();
FileOutputStream targetStream = null;
if (targetStream != null)
try {
targetStream.close();
sourceStream = new
}
FileInputStream("sorcefile.txt");
}
targetStream = new
FileOutputStream("targetfile.txt"); }
Example- CharacterStream
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws
IOException { finally {
FileReader in = null; if (in != null) {
FileWriter out = null; in.close();
try { }
in = new FileReader("input.txt"); if (out != null) {
out = new FileWriter("output.txt"); out.close();
int c; }
while ((c = in.read()) != -1) { }
out.write(c); }
} }
}
file handling - Using java.io Package
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IOExample {
public static void main(String args[]) {
try {
File file = new File("example.txt"); // File object
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
System.out.println(reader.nextLine()); }
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!"); } }}
Output (if example.txt contains Hello Java!):
Hello Java! 15