0% found this document useful (0 votes)
24 views18 pages

Java File Handling Basics Explained

The document provides an overview of file handling in Java, explaining the concepts of files and directories, as well as the importance of file operations such as creating, reading, writing, and deleting files. It details various methods available in the Java File class for performing these operations and includes code examples for practical understanding. Additionally, it discusses creating directories and renaming files using specific Java methods.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views18 pages

Java File Handling Basics Explained

The document provides an overview of file handling in Java, explaining the concepts of files and directories, as well as the importance of file operations such as creating, reading, writing, and deleting files. It details various methods available in the Java File class for performing these operations and includes code examples for practical understanding. Additionally, it discusses creating directories and renaming files using specific Java methods.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

File Handling in Java

File and Directory

A file is a named location that can be used to store related information. For example, [Link] is a Java file
that contains information about the Java program. A directory is a collection of files and subdirectories. A
directory inside a directory is known as subdirectory.

Why File Handling is Required?

 File Handling is an integral part of any programming language as file handling enables us to store the
output of any particular program in a file and allows us to perform certain operations on it.

 In simple words, file handling means reading and writing data to a file.

File Operations in Java

In Java, a File is an abstract data type. A named


location used to store related information is known as
a File. There are several File
Operations like creating a new File, getting
information about File, writing into a File,
reading from a File and deleting a File.

Before understanding the File operations, it is required


that we should have knowledge of Stream and File
methods. If you have knowledge about both of them,
you can skip it.

Stream - A series of data is referred to as a stream.


In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.

Byte Stream - Byte Stream is mainly involved with


byte data. A file handling process with a byte stream is
a process in which an input is provided and executed
with the byte data.

Character Stream - Character Stream is mainly


involved with character data. A file handling process
with a character stream is a process in which an input
is provided and executed with the character data.

Java File Class Methods

S. Method Return Description


N. Type
1. canRead() Boolea The canRead() method is used to check whether we can read the data of
n the file or not.
2. createNewFile() Boolea The createNewFile() method is used to create a new empty file.
n
3. canWrite() Boolea The canWrite() method is used to check whether we can write the data
n into the file or not.
4. exists() Boolea The exists() method is used to check whether the specified file is present
n or not.
5. delete() Boolea The delete() method is used to delete a file.
n
6. getName() String The getName() method is used to find the file name.
7. getAbsolutePat String The getAbsolutePath() method is used to get the absolute pathname of
h() the file.
8. length() Long The length() method is used to get the size of the file in bytes.
9. list() String[] The list() method is used to get an array of the files available in the
directory.
10. mkdir() Boolea The mkdir() method is used for creating a new directory.
n
Create a Java File Object

To create an object of File, we need to import the [Link] package first. Once we import the package, here
is how we can create objects of file.

// creates an object of File using the path


File file = new File(String pathName);

Here, we have created a file object named file. The object can be used to work with files and directories.

Note: In Java, creating a file object does not mean creating a file. Instead, a file object is an abstract
representation of the file or directory pathname (specified in the parenthesis).

Java File Operation Methods

Operation Method Package


To create file createNewFile() [Link]
To read file read() [Link]
To write file write() [Link]
To delete file delete() [Link]

File Operations

We can perform the following operation on a file:

Create a File

Create a File operation is performed to create a new file. We use the createNewFile() method of file.
The createNewFile() method returns true when it successfully creates a new file and returns false when the
file already exists. Let's take an example of creating a file to understand how we can use
the createNewFile() method to perform this operation.

// Importing File class


import [Link];
// Importing the IOException class for handling errors
import [Link];
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:[Link]");
if ([Link]()) {
[Link]("File " + [Link]() + " is created successfully.")
;
} else {
[Link]("File is already exist in the directory.");
}
} catch (IOException exception) {
[Link]("An unexpected error is occurred.");
[Link]();
}
}
}

Explanation: In the above code, we import the File and IOException class for performing file operation and
handling errors, respectively. We create the f0 object of the File class and specify the location of the directory
where we want to create a file. In the try block, we call the createNewFile() method through the f0 object to
create a new file in the specified location. If the method returns false, it will jump to the else section. If there is
any error, it gets handled in the catch block.

Get File Information

The operation is performed to get the file information. We use several methods to get the information about
the file like name, absolute path, is readable, is writable and length. Let's take an example to understand how
to use file methods to get the information of the file.

[Link]

// Import the File class


import [Link];
class FileInfo {
public static void main(String[] args) {
// Creating file object
File f0 = new File("D:[Link]");
if ([Link]()) {
// Getting file name
[Link]("The name of the file is: " + [Link]());

// Getting path of the file


[Link]("The absolute path of the file is: " + [Link]());

// Checking whether the file is writable or not


[Link]("Is file writeable?: " + [Link]());

// Checking whether the file is readable or not


[Link]("Is file readable " + [Link]());

// Getting the length of the file in bytes


[Link]("The size of the file in bytes is: " + [Link]());
} else {
[Link]("The file does not exist.");
}
}
}

Output:
Description: In the above code, we import the [Link] package and create a class FileInfo. In the main
method, we create an object of the text file which we have created in our previous example. We check the
existence of the file using a conditional statement, and if it is present, we get the following information about
that file:

1. We get the name of the file using the getName()


2. We get the absolute path of the file using the getAbsolutePath() method of the file.
3. We check whether we can write data into a file or not using the canWrite()
4. We check whether we can read the data of the file or not using the canRead()
5. We get the length of the file by using the length()

If the file doesn't exist, we show a custom message.

Write to a File

The next operation which we can perform on a file is "writing into a file". In order to write data into a file, we
will use the FileWriter class and its write() method together. We need to close the stream using
the close() method to retrieve the allocated resources. Let's take an example to understand how we can write
data into a file.

[Link]

// Importing the FileWriter class


import [Link];
// Importing the IOException class for handling errors
import [Link];

class WriteToFile {
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("D:[Link]");
// writing the content into the [Link] file
[Link]("A named location used to store related information is referred to as a
File.");
// Closing the stream
[Link]();
[Link]("Content is successfully wrote to the file.");
} catch (IOException e) {
[Link]("Unexpected error occurred");
[Link]();
}
}
}

Output:
Explanation: In the above code, we import the [Link] and [Link] classes. We
create a class WriteToFile, and in its main method, we use the try-catch block. In the try section, we create an
instance of the FileWriter class, i.e., fwrite. We call the write method of the FileWriter class and pass the
content to that function which we want to write. After that, we call the close() method of the FileWriter class
to close the file stream. After writing the content and closing the stream, we print a custom message.

If we get any error in the try section, it jumps to the catch block. In the catch block, we handle
the IOException and print a custom message.

Read from a File

The next operation which we can perform on a file is "read from a file". In order to write data into a file, we
will use the Scanner class. Here, we need to close the stream using the close() method. We will create an
instance of the Scanner class and use the hasNextLine() method nextLine() method to get data from the
file. Let's take an example to understand how we can read data from a file.

[Link]

// Importing the File class


import [Link];
// Importing FileNotFoundException class for handling errors
import [Link];
// Importing the Scanner class for reading text files
import [Link];

class ReadFromFile {
public static void main(String[] args) {
try {
// Create f1 object of the file to read data
File f1 = new File("D:[Link]");
Scanner dataReader = new Scanner(f1);
while ([Link]()) {
String fileData = [Link]();
[Link](fileData);
}
[Link]();
} catch (FileNotFoundException exception) {
[Link]("Unexcpected error occurred!");
[Link]();
}
}
}

Output:
Expalnation: In the above code, we import the "[Link]",
"[Link]" and "[Link]" classes. We create a class ReadFromFile, and in its main method,
we use the try-catch block. In the try section, we create an instance of both the Scanner and
the File classes. We pass the File class object to the Scanner class object and then iterate the scanner class
object using the "While" loop and print each line of the file. We also need to close the scanner class object, so
we use the close() function. If we get any error in the try section, it jumps to the catch block. In the catch
block, we handle the IOException and print a custom message.

Delete a File

The next operation which we can perform on a file is "deleting a file". In order to delete a file, we will use
the delete() method of the file. We don't need to close the stream using the close() method because for
deleting a file, we neither use the FileWriter class nor the Scanner class. Let's take an example to understand
how we can write data into a file.

[Link]

// Importing the File class


import [Link];
class DeleteFile {
public static void main(String[] args) {
File f0 = new File("D:[Link]");
if ([Link]()) {
[Link]([Link]()+ " file is deleted successfully.");
} else {
[Link]("Unexpected error found in deletion of the file.");
}
}
}

Output:

Explanation: In the above code, we import the File class and create a class DeleteFile. In the main() method
of the class, we create f0 object of the file which we want to delete. In the if statement, we call
the delete() method of the file using the f0 object. If the delete() method returns true, we print the success
custom message. Otherwise, it jumps to the else section where we print the unsuccessful custom message.

All the above-mentioned operations are used to read, write, delete, and create file programmatically.

Java Program to Create Directories

The Java File class provides the mkdir() method to create a new directory. The method returns
 true if the new directory is created
 false if the directory already exists

Example 1: Create a new directory in Java

import [Link];
class Main {
public static void main(String[] args) {
// creates a file object with specified path
File file = new File("Java Example\\directory");
// tries to create a new directory
boolean value = [Link]();
if(value) {
[Link]("The new directory is created.");
}
else {
[Link]("The directory already exists.");
}
}
}

In the above example, we have created a file object named file. The object includes information about the
specified directory path.

File file = new File("Java Example\\directory");

Here, we have used the mkdir() method to create a new directory in the specified path.

If the directory doesn't exist in the specified location, the new directory is created and this message is
shown.

The new directory is created.

However, if the directory already exists, we will see this message.

The directory already exists.

It is important to note that, the directory is created inside the Java Example parent directory.

However, if the Java Example parent directory doesn't exist, then the mkdir() method cannot create
the directory.

In this case, we can use the mkdirs() method of the Java File class. The method allows us to create the parent
directory as well if it's not already there.

Example 2: Create a new Directory using the mkdirs() method

import [Link];
class Main {
public static void main(String[] args) {
// creates a file object in the current path
File file = new File("Java Tutorial\\directory");
// tries to create a new directory
boolean value = [Link]();
if(value) {
[Link]("The new directory is created.");
}
else {
[Link]("The directory already exists.");
}
}
}

In the above example, we have created a file object named file. The object includes information about the
directory path.
File file = new File("Java Tutorial\\directory");

Here, we have used the mkdirs() method to create a new directory with the specified path.

If the directory doesn't exist in the current location, the new directory is created and this message is
shown.

The new directory is created.

However, if the directory already exists, we will see this message.

The directory already exists.

Here, if the Java Tutorial directory doesn't exist, then the mkdirs() method creates the Java
Tutorial directory as well along with the directory.

Note: We have used double-backslash while specifying the path. It is because the \ character is used as
an escape character in Java. Hence the first backslash is used as an escape character for the second one.

Java Program to Rename File

The Java File class provides the renameTo() method to change the name of the file. It returns true if the
renaming operation succeeds otherwise returns false.

Example: Rename a File in Java

import [Link];
class Main {
public static void main(String[] args) {
// create a file object
File file = new File("oldName");

// create a file
try {
[Link]();
}
catch(Exception e) {
[Link]();
}

// create an object that contains the new name of file


File newFile = new File("newName");

// change the name of file


boolean value = [Link](newFile);

if(value) {
[Link]("The name of the file is changed.");
}
else {
[Link]("The name cannot be changed.");
}
}
}

In the above example, we have created a file object named file. The object holds information about the
specified file path.

File file = new File("oldName");

We then create a new file with the specified file path.

// create a new file with the specified path


[Link]();
Here, we have created another file object named newFile. The object holds information about the specified file
path.

File newFile = new File("newFile");

To change the name of the file, we have used the renameTo() method. The name specified by
the newFile object is used to rename the file specified by the file object.

[Link](newFile);

If the operation succeeds, then the following message is shown.

The name of the file is changed.

If the operation cannot succeed, the following message is shown.

The name cannot be changed.

Java Program to Get all Files Present in a Directory

The list() method of the Java File class is used to list all the files and subdirectories present inside a directory. It
returns all the files and directories as a string array.

Example 1: Java Program to List all files

import [Link];
class Main {
public static void main(String[] args) {
// creates a file object
File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");

// returns an array of all files


String[] fileList = [Link]();

for(String str : fileList) {


[Link](str);
}
}
}

Output

.vscode
[Link]
directory
[Link]

In the above example, we have created a file object named file. The object holds information about the
specified path.

File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");

We have used the list() method to list all the files and subdirectories present in the specified path.

[Link]();

Note: We have used double-backslash while specifying the path. It is because the \ character is used as
an escape character in Java. Hence the first backslash is used as an escape character for the second one.

Example 2: List files present in a Directory excluding Subdirectories

import [Link];
class Main {
public static void main(String[] args) {
try {
File folder = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Java Article");
// list all the files
File[] files = [Link]();
for(File file : files) {
if([Link]()) {
[Link](file);
}
}
} catch (Exception e) {
[Link]();
}
}
}

Output

C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]
C:\Users\Unknown\Desktop\Java Article\[Link]

In the above example, we have used the listFiles() method to store all files in an array.

Java Program to Copy File

The Java File class doesn't provide any method to copy one file to another. However, we can use Java I/O
Streams to read content from one file and write to another.

Example: Copy files using i/o streams

import [Link];
import [Link];
class Main {
public static void main(String[] args) {
byte[] array = new byte[50];
try {
FileInputStream sourceFile = new FileInputStream("[Link]");
FileOutputStream destFile = new FileOutputStream("newFile");

// reads all data from [Link]


[Link](array);

// writes all data to newFile


[Link](array);
[Link]("The [Link] file is copied to newFile.");

// closes the stream


[Link]();
[Link]();
}
catch (Exception e) {
[Link]();
}
}
}

Output

The [Link] file is copied to newFile.

In the above example, we have used the FileInputStream and FileOutputStream to copy one file to another.

Here,
 FileInputStream reads all the content from [Link] to an array
 FileOutputStream writes all the content from the array to newFile

Note:

 The FileUtils class of [Link] package provides the copyFile() method to copy the file.
 The Files class of [Link] package provides the copy() method to copy the file.

Java File Class in Detail

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. Following is the list of constructors to create a File object.

S. Method & Description


N.
1 File(File parent, String child) - This constructor creates a new File instance from a parent abstract
pathname and a child pathname string.
2 File(String pathname) - This constructor creates a new File instance by converting the given
pathname string into an abstract pathname.
3 File(String parent, String child) - This constructor creates a new File instance from a parent
pathname string and a child pathname string.
4 File(URI uri) - This constructor creates a new File instance by converting the given file: URI into an
abstract pathname.

Once you have File object in hand, then there is a list of helper methods which can be used to manipulate the
files.

S. Method & Description


N.
1 public String getName() - Returns the name of the file or directory denoted by this abstract
pathname.
2 public String getParent() - Returns the pathname string of this abstract pathname's parent, or null
if this pathname does not name a parent directory.
3 public File getParentFile() - Returns the abstract pathname of this abstract pathname's parent, or
null if this pathname does not name a parent directory.
4 public String getPath() - Converts this abstract pathname into a pathname string.
5 public boolean isAbsolute() - Tests whether this abstract pathname is absolute. Returns true if this
abstract pathname is absolute, false otherwise.
6 public String getAbsolutePath() - Returns the absolute pathname string of this abstract
pathname.
7 public boolean canRead() - Tests whether the application can read the file denoted by this abstract
pathname. Returns true if and only if the file specified by this abstract pathname exists and can be
read by the application; false otherwise.
8 public boolean canWrite() - Tests whether the application can modify to the file denoted by this
abstract pathname. Returns true if and only if the file system actually contains a file denoted by this
abstract pathname and the application is allowed to write to the file; false otherwise.
9 public boolean exists() - Tests whether the file or directory denoted by this abstract pathname
exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false
otherwise.
10 public boolean isDirectory() - Tests whether the file denoted by this abstract pathname is a
directory. Returns true if and only if the file denoted by this abstract pathname exists and is a
directory; false otherwise.
11 public boolean isFile() - Tests whether the file denoted by this abstract pathname is a normal file. A
file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any
non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and
only if the file denoted by this abstract pathname exists and is a normal file; false otherwise.
12 public long lastModified() - Returns the time that the file denoted by this abstract pathname was
last modified. Returns a long value representing the time the file was last modified, measured in
milliseconds since the epoch ([Link] GMT, January 1, 1970), or 0L if the file does not exist or if an
I/O error occurs.
13 public long length() - Returns the length of the file denoted by this abstract pathname. The return
value is unspecified if this pathname denotes a directory.
14 public boolean createNewFile() throws IOException - Atomically creates a new, empty file
named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if
the named file does not exist and was successfully created; false if the named file already exists.
15 public boolean delete() - Deletes the file or directory denoted by this abstract pathname. If this
pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true
if and only if the file or directory is successfully deleted; false otherwise.
16 public void deleteOnExit() - Requests that the file or directory denoted by this abstract pathname
be deleted when the virtual machine terminates.
17 public String[] list() - Returns an array of strings naming the files and directories in the directory
denoted by this abstract pathname.
18 public String[] list(FilenameFilter filter) - Returns an array of strings naming the files and
directories in the directory denoted by this abstract pathname that satisfy the specified filter.
20 public File[] listFiles() - Returns an array of abstract pathnames denoting the files in the directory
denoted by this abstract pathname.
21 public File[] listFiles(FileFilter filter) - Returns an array of abstract pathnames denoting the files
and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
22 public boolean mkdir() - Creates the directory named by this abstract pathname. Returns true if
and only if the directory was created; false otherwise.
23 public boolean mkdirs() - Creates the directory named by this abstract pathname, including any
necessary but nonexistent parent directories. Returns true if and only if the directory was created,
along with all necessary parent directories; false otherwise.
24 public boolean renameTo(File dest) - Renames the file denoted by this abstract pathname.
Returns true if and only if the renaming succeeded; false otherwise.
25 public boolean setLastModified(long time) - Sets the last-modified time of the file or directory
named by this abstract pathname. Returns true if and only if the operation succeeded; false
otherwise.
26 public boolean setReadOnly() - Marks the file or directory named by this abstract pathname so
that only read operations are allowed. Returns true if and only if the operation succeeded; false
otherwise.
27 public static File createTempFile(String prefix, String suffix, File directory) throws
IOException - Creates a new empty file in the specified directory, using the given prefix and suffix
strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.
28 public static File createTempFile(String prefix, String suffix) throws IOException - Creates
an empty file in the default temporary-file directory, using the given prefix and suffix to generate its
name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null). Returns
abstract pathname denoting a newly-created empty file.
29 public int compareTo(File pathname) - Compares two abstract pathnames lexicographically.
Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument.
30 public int compareTo(Object o) - Compares this abstract pathname to another object. Returns zero
if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract pathname is
lexicographically greater than the argument.
31 public boolean equals(Object obj) - Tests this abstract pathname for equality with the given
object. Returns true if and only if the argument is not null and is an abstract pathname that denotes
the same file or directory as this abstract pathname.
32 public String toString() - Returns the pathname string of this abstract pathname. This is just the
string returned by the getPath() method.

Working with Input/output APIs

Java I/O Tutorial

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the classes
required for input and output operations.

We can perform file handling in Java by Java I/O API.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a
stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) [Link]: standard output stream


2) [Link]: standard input stream
3) [Link]: standard error stream

Let's see the code to print output and an error message to the console.

[Link]("simple message");
[Link]("error message");

Let's see the code to get input from console.

int i=[Link]();//returns ASCII code of 1st character


[Link]((char)i);//will print the character

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream - Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

InputStream - Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket. Let's understand the working of Java OutputStream and InputStream by the figure
given below.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of
bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description
1) public void write(int)throws is used to write a byte to the current output stream.
IOException
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

OutputStream Hierarchy
InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method Description
1) public abstract int reads the next byte of data from the input stream. It returns -1 at the end of
read()throws the file.
IOException
2) public int returns an estimate of the number of bytes that can be read from the current
available()throws input stream.
IOException
3) public void is used to close the current input stream.
close()throws
IOException

InputStream Hierarchy

Java FileOutputStream Class

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 [Link] class:

public class FileOutputStream extends OutputStream

FileOutputStream class methods

Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write [Link] bytes from the byte array to the file output
stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting at offset off to the
off, int len) file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
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.
void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte

import [Link];
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\[Link]");
[Link](65);
[Link]();
[Link]("success...");
}catch(Exception e){[Link](e);}
}
}

Output:

Success...

The content of a text file [Link] is set with the data A.

[Link]

Java FileOutputStream example 2: write string

1. import [Link];

2. public class FileOutputStreamExample {

3. public static void main(String args[]){

4. try{

5. FileOutputStream fout=new FileOutputStream("D:\\[Link]");

6. String s="Welcome to javaTpoint.";

7. byte b[]=[Link]();//converting string into byte array

8. [Link](b);

9. [Link]();

10. [Link]("success...");
11. }catch(Exception e){[Link](e);}

12. }

13. }

Output:

Success...

The content of a text file [Link] is set with the data Welcome to javaTpoint.

[Link]

Welcome to javaTpoint.

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 [Link] class:

1. public class FileInputStream extends InputStream

Java FileInputStream class methods

Method Description

int available() It is used to return the estimated number of bytes that can be read from the input stream

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to [Link] bytes of data from the input stream.

int read(byte[] b, int off, int It is used to read up to len bytes of data from the input stream.
len)

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.

protected void finalize() It is used to ensure that the close method is call when there is no more reference t
stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

1. import [Link];

2. public class DataStreamExample {

3. public static void main(String args[]){

4. try{

5. FileInputStream fin=new FileInputStream("D:\\[Link]");

6. int i=[Link]();

7. [Link]((char)i);

8.

9. [Link]();

10. }catch(Exception e){[Link](e);}

11. }

12. }

Note: Before running the code, a text file named as "[Link]" is required to be created. In this file, we are
having following content:

Welcome to javatpoint.

After executing the above program, you will get a single character from the file which is 87 (in byte form). To
see the text, you need to convert it into character.

Output:

Java FileInputStream example 2: read all characters

1. package [Link];

2.

3. import [Link];

4. public class DataStreamExample {

5. public static void main(String args[]){

6. try{

7. FileInputStream fin=new FileInputStream("D:\\[Link]");

8. int i=0;
9. while((i=[Link]())!=-1){

10. [Link]((char)i);

11. }

12. [Link]();

13. }catch(Exception e){[Link](e);}

14. }

15. }

Output:

Welcome to javaTpoint

You might also like