0% found this document useful (0 votes)
1 views55 pages

Java Exception

Uploaded by

Pandiaraj A
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)
1 views55 pages

Java Exception

Uploaded by

Pandiaraj A
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

Java I/O | I/O Streams in Java

The [Link] package is used to handle input and output operations. Java IO has
various classes that handle input and output sources. A stream is a sequence of
data.

Java input stream classes can be used to read data from input sources such
as keyboard or a file. Similarly output stream classes can be used to write data on
a display or a file again.

We can also perform File Handling using Java IO API.

Introduction to I/O Streams in Java


Before understanding IO streams, let us discuss streams. A Stream is also a
sequence of data. It is neither a data structure nor a store of data. For example, a
river stream is where water flows from source to destination. Similarly, these are
data streams; data flows through one point to another.

We introduce a term called IO streamsto handle these sequences.

The [Link] package helps the user perform all input-output operations.
Java IO package is primarily focused on input-output files, network streams,
internal memory buffers, etc. Data is read and written from Java
IO's InputStream and OutputStream classes.

In other words, IO streams in Java help to read the data from an input stream, such
as a file and write the data into an output stream, such as the standard display or a
file again. It represents the source as input and the destination as output. It can
handle all types of data, from primitive values to advanced objects.

What is Java IO?


The [Link] package consists of output and input streams used to write and read
data to files or other output and input sources.

There are 3 categories of classes in [Link] package:

 Input Streams.
 Output Streams.
 Error Streams.

Java supports three streams that are automatically attached with the console.

1. [Link]: Standard output stream


2. [Link]: Standard input stream
3. [Link]: Standard error stream

Input Streams
As we know, an input source consists of data that needs to be read in order to
extract information from it. Input Streams help us read data from the input source.
They are an abstract class that provides a programming interface for all input
streams.

Input streams are opened implicitly as soon as they are created. We use
a close() method on the source object to close the input stream.

Output Streams
The executed program's output must be stored in a file for further use. Output
streams help us write data to an output source(such as a file). Similarly to input
streams, output streams are abstract classes that provide a programming interface
for all output streams.

The output stream is opened as soon as it is created and explicitly closed using the
"close() "method.

Error Streams
Error streams are the same as output streams. In some ide’s, the error is displayed
in different colors (other than the color of the output color). It gives output on the
console the same as output streams.

Why We Need IO Streams in Java?


In daily work, we do not enter input into programs manually. Also, the program's
result needs to be stored somewhere for further use.

So, Java IO streams provide input and output streams that help us extract data from
files and write the data into them. Normally, we can create, delete, and edit files
using [Link].

In short, all file manipulation is done using "Java IO streams, " which also handle
user input functionality.

Types of Streams in Java


Depending on the types of operations, streams are divided into 2 primary classes.
Input Stream
It is an abstract superclass of the [Link] package and is used to read the data from
an input source. In other words, it means reading data from files, using a keyboard,
etc. We can create an object of the input stream class using the new keyword. The
input stream class has several types of constructors.

The following code takes the file name as a string, to read the data stored in the
file.
InputStream f = new FileInputStream("[Link]");

InputStream Hierarchy

Useful methods of InputStream

1. public abstract int read() throws IOException

The method above returns the data of the next byte in the input stream. The value
returned is between 0and 255. If no byte is read, the code returns -1, indicating the
file's end.

2. public int available() throws IOException

The method above returns the number of bytes that can be read from the input
stream.

3. public void close() throws IOException

The method above closes the current input stream and releases any associated
system resources.

4. public void mark(int readlimit)


It marks the current position in the input stream. The readlimit argument tells the
input stream to read that many bytes before the mark position becomes invalid.

5. public boolean markSupported()

It tells whether a particular input stream supports the mark() and reset() method. It
returns true if the particular input stream supports the mark and reset methods or
returns false.

6. public int read(byte[ ] b) throws IOException

The method above reads the bytes from the input stream and stores every byte in
the buffer array. It returns the total number of bytes stored in the buffer array.
If there is no byte in the input stream, it returns -1 as the stream is at the end of the
file.

7. public int read(byte[ ] b , int off , len) throws IOException

It reads up to len bytes of data from the input stream and returns the total number
of bytes stored in the buffer. Here, the “off” is the start offset in buffer
array b where the data is written, and the “len” represents the maximum number of
bytes to read.

8. public void reset() throws IOException

It repositions the stream to the last called mark position. The reset method does
nothing for input stream class except throwing an exception.

9. public long skip(long n) throws IOException

This method discards n bytes of data from the input stream.

Examples
1. In the below example, we will use FileInputStream class to read the input
file: [Link].

 Create a file [Link] and place it in the same directory as [Link]


 Let us suppose [Link] contains the following content:
Scaler Topics
From InterviewBit

Code:
import [Link].*;
class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f variable
FileInputStream f = new FileInputStream("[Link]");

// initializing x to 0
int x = 0;
// while loop untill the end of the file.
while ((x = [Link]()) != -1) {
// printing the character
[Link]((char) x);
}
// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:
Scaler Topics
From InterviewBit

2. In the below example, we will use BufferedInputStream class to read the


file.

Code:
import [Link].*;

class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f1 variable using FileInputStream
FileInputStream f1 = new FileInputStream("[Link]");

// loading a file into f2 variable using


BufferInputStream
BufferedInputStream f2 = new BufferedInputStream(f1);

// using the available method


[Link]("Available bytes: " +
[Link]());
int x = 0;
// while loop untill the end of the file.
while ((x = [Link]()) != -1) {
// printing the character
[Link]((char) x);
}
[Link]();
// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:
Available bytes: 31
Scaler Topics
From InterviewBit

3. In the below example, we will use the ByteArrayInputStream class to read


the file.

Code:
import [Link].*;

class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f1 variable using FileInputStream
FileInputStream f1 = new FileInputStream("[Link]");

int x = 0;
String S = "";
// while loop untill the end of the file.
while ((x = [Link]()) != -1) {
// printing the character
S = S + (char) x;
}
// closing a input stream
[Link]();

// converting string to array of bytes


byte[] b = [Link]();
// declaring ByteArrayInputStream
ByteArrayInputStream b1 = new ByteArrayInputStream(b);

x = [Link]();
while (x != -1) {
[Link]((char) x);
x = [Link]();
}
[Link]();
// close the input stream
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:
Scaler Topics
From InterviewBit

Output Stream
It is an abstract superclass of the [Link] package that writes data to an output
resource, which is, in other words, writing the data into files. We can create an
object of the output stream class using the new keyword. The output stream class
has several types of constructors.

OutputStream Hierarchy

Useful methods of OutputStream


1. public void close() throws IOException
This method closes the current output stream and releases any associated system
resources. The closed stream cannot be reopened, and operations cannot be
performed on it.

2. public void flush() throws IOException

It flushes the current output stream and forces any buffered output to be written
out.

3. Public void write(byte[ ] b) throws IOException

This method writes the [Link] bytes from the specified byte array to the output
stream.

4. Public void write(byte[ ] b ,int off ,int len) throws IOException

It writes up to len bytes of data for the output stream. Here, the “off” is the start
offset in buffer array b, and the “len” represents the maximum number of bytes to
be written in the output stream.

5. Public abstract void write(int b) throws IOException

The method above writes the specific bytes to the output stream. It does not return
a value.

Quiz Pop

Quiz Type
SCQ
100
Success Rate:35%

What does the InputStream class in Java represent?


A sequence of characters.
A sequence of data read from an input source.
A sequence of bytes written to an output source.
A sequence of graphical elements.
Submit

Some methods that are inherited from class [Link]. These methods are
used for both input stream and output stream purposes.

Example: clone, equals, finalise, getclass, hashCode, notify, notifyAll, toString,


wait.

Examples
1. In the example below, we will use the FileOutputStream class to read the
file.

Code:
import [Link].*;

class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f variable
FileOutputStream f = new FileOutputStream("[Link]");

String s = "Scaler Topics";


char arr[] = [Link]();
// initializing x to 0
int x = 0;
// while loop untill the end of the string.
while (x < [Link]()) {
// writing a byte into "[Link]" file
[Link](arr[x++]);
}
// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

The [Link] file will contain the following text:


Scaler Topics

2. In the example below, we will use the BufferedOutputStream class to read


the file.

Code:
import [Link].*;

class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f variable
FileOutputStream f1 = new
FileOutputStream("[Link]");

// declaring a f1 as BufferedOutputStream
BufferedOutputStream f2 = new BufferedOutputStream(f1);

String s = "Scaler Topics";


char arr[] = [Link]();
// initializing x to 0
int x = 0;
// while loop untill the end of the string.
while (x < [Link]()) {
// writing a byte into "[Link]" file
[Link](arr[x++]);
}
// closing a file
[Link]();
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

The [Link] file will contain the following text:


Scaler Topics

3. In the below example, we will use the ByteArrayOutputStream class to


read the file.

Code:
import [Link].*;

class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f variable
FileOutputStream f = new FileOutputStream("[Link]");

String s = "Scaler Topics";

// declaring ByteArrayOutputStream
ByteArrayOutputStream b1 = new ByteArrayOutputStream();
// writing a data to "[Link]" file
[Link]([Link]());
[Link](f);

// closing a file
[Link]();
} catch (Exception e) {
// printing exception
[Link](e);
}
}
}

Output:

The [Link]`` file will contain the following text:


Scaler Topics
Quiz Pop

Quiz Type
SCQ
100
Success Rate:35%

What is the purpose of the BufferedInputStream class in Java?


To read data from an input source with buffering.
To write data to an output source with buffering.
To handle errors in the input stream.
To manage memory allocation for input streams.
Submit

Conclusion
 Java has three main types of IO streams.
o Input Streams
o Output Streams
o Error Streams
 Input Stream and Output Stream are abstract superclasses of
the [Link] package.
 Input and Output Streams are used to read data from input sources (such as
Standard Input) and write data into output sources (such as files and
consoles).
Challenge Time!
Time to test your skills and win rewards!Start ChallengeNote: Rewards will be
credited after the next product update.
1
Scroll to top!
Java
How would you rate this article?

Updated - 9 Jul 20247 mins readPublished : 5 Mar 2022


Written By

Byte Stream and Character Stream

Overview
The stream method helps to sequentially access a file. There are two types
of streams in Java - Byte Stream and Character Stream. Byte streams in Java are
used to perform input and output operations of 8-bit bytes while the Character
stream is used to perform input and output operations for 16-bits Unicode.

Character streams are useful in reading or writing text files which are processed
character by character. Byte Streams are useful to read/write data from raw binary
files.

Introduction to Byte Stream and Character Stream


Have you ever wondered, how the various files that we write in Java are accessed
and processed or how Java internally manages to handle operations on such files?
Suppose, if we want to copy a file from our laptop to a pen drive, how does that
happen?

An I/O (Input/Output) stream is used to represent an input source or an output


destination. It can represent many kinds of sources and destinations like disc files
(systems that manage data on permanent storage devices eg. hard disc or magnetic
disc) or devices.

The stream method helps to sequentially access a file. Some streams simply pass
on the data while some manipulate and transform the data in a useful way. For
example, some streams copy the contents of the file to another and do not modify
them or some streams perform manipulations on them like adding or filtering data
etc. Streams support many kinds of data including bytes, primitive data types,
characters and objects.

The [Link] package contains classes that allow the user to convert between
Unicode character streams and byte streams of non-Unicode text.

In the above image, we are converting non-Unicode bytes to Unicode characters


and vice-versa using InputStreamReader and OutputStreamWriter classes
respectively.

Let us understand some terminologies associated with the same.

 Stream- It is a sequence of data/objects that supports various methods. They


are used to read or write data. Eg- files, input-output devices etc.
 Input Stream Reader- It reads data from a source, one item at a time.
An InputStreamReader class is a bridge from byte streams to character
streams. It reads bytes and decodes them into characters.
 Output Stream Writer- It writes data to a destination, one item at a time.
An OutputStreamWriter class is a bridge from character streams to byte
streams. Characters written to it are encoded into bytes.
 Unicode is an international character encoding standard by which each
letter, digit or symbol is assigned a unique numeric value across all
platforms.
 Non-Unicode text are modules or character encodings that do not support
Unicode standards. It only supports English language representation.
What is Byte Stream in Java?
Byte streams are used to perform input and output of 8-bit bytes. They are used
to read bytes from the input stream and write bytes to the output stream. Mostly,
they are used to read or write raw binary data.

In Java, the byte streams have a 3 phase mechanism:

 Split- The input data source is split into a stream by a spliterator.


Java Spliterator interface is an internal iterator that breaks the stream into
smaller parts for traversing over them.
 Apply- The elements in the stream are processed.
 Combine- After the elements are processed, they are again combined
together to create a single result.

Java provides many byte stream classes, but the most common ones are-

FileInputStream- This class is used to read data from a file/source. The


FileInputStream class has constructors which we can use to create an instance of
the FileInputStream class.

Syntax:
FileInputStream sourceStream = new
FileInputStream("path_to_file");

FileOutputStream- This class is used to write data to the destination. The


following is the constructor to create an instance of the FileOutputStream class.

Syntax:
FileOutputStream targetStream = new
FileOutputStream("path_to_file");
The above image shows an example of the byte stream. From a program, the bytes
are being transferred in the form of a stream to the destination.

Example of Byte Stream


Let us take a look at an example to use Byte Stream to copy the contents of one file
to another. In the example, we will create two objects of the FileInputStream and
the FileOutputStream classes.

The source and the destination files names are given as parameters to
the FileInputStream and the FileOutputStream classes respectively. Then the
content of the source file will be copied to the destination file.
import [Link].*;
public class ByteStreamExample
{
public static void main(String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;

try
{
sourceStream = new FileInputStream("[Link]");
targetStream = new FileOutputStream
("[Link]");

// Reading source file using read method


// and write to file byte by byte using write
method
int temp;
while ((temp = [Link]()) != -1)
[Link]((byte)temp);
}
finally
{
if (sourceStream != null){
[Link]();
}
if (targetStream != null){
[Link]();
}
}
}
}

Explanation- Let us assume that we have already created a file


named [Link] which has the following content-
101000010001111111

After we execute the above program, it will create a file called [Link] in
the same directory as the program file which has the same content as of [Link].
If a file with the same name already exists, an exception
of FileAlreadyExistsException is thrown. Use this Java Online Compiler to
compile your code.

What is Character Stream in Java?


In Java, character values are stored using Unicode conventions. As we saw above,
the Byte stream is used to perform input and output operations of 8-bit bytes, but
the Character stream is used to perform input and output operations of 16-bit
Unicode. If we want to copy a text file containing characters from one source to
another destination using streams, character streams would be advantageous as it
deals with characters. Characters in Java are 2 bytes or 16 bits in size.

In Java, the character streams too have a 3 phase mechanism similar to that of Byte
Streams as explained above.

Java provides many character stream classes, but the most common ones
are- FileReader- It is used to read two bytes at a time from the source. The
following is the constructor to create an instance of the FileReader class.
FileReader in = new FileReader("path_to_file");

FileWriter- It is used to write two bytes at a time to the destination. The following
is the constructor to create an instance of the FileWriter class.
FileWriter in = new FileWriter("path_to_file");

Example of Character Stream


This example deals with the usage of Character Stream to copy the contents of one
file to another. In the example, we will create two objects of the FileReader and
the FileWriter classes. The source and the destination files names are given as
parameters to the FileReader and the FileWriter classes respectively. Then the
content of the source file will be copied to the destination file.
import [Link].*;
public class CharacterStreamExample {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

// Reading source file using read method


// and write to file using write method
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}
finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

Explanation - Let us assume that we have already created a file


named [Link] which has the following content-
Hi, we are learning about character stream.

After we execute the above program, it will create a file


called [Link] which has the same content as of [Link]. If a file with the
same name already exists, an exception of FileAlreadyExistsException is thrown.

Difference Between Byte Stream and Character Stream


Byte Stream Character Stream
Byte stream is used to perform input and Character stream is used to perform input
output operations of 8-bit bytes. and output operations of 16-bit Unicode.
Byte Stream Character Stream
It processes data byte by byte. It processes data character by character.
Common classes for Byte stream are Common classes for Character streams are
FileInputStream and FileOutputStream. FileReader and FileWriter.
Example- Byte streams are used to read or Example- Character streams are used to
write binary data. read/write characters.

When to use Character Stream over Byte Stream?


Character streams are used when we want to process text files. As we know Java
stores characters in Unicode format. Character stream processes data character by
character. Character stream performs input and output operations of 16-bit
Unicode which is equivalent to the size of a character in Java.

Example- Character streams are used to read/write characters.

When to use Byte Stream over Character Stream?


Byte streams are used to process raw data like binary files. If we have a file that
contains binary data, then it will be appropriate to use Byte stream. They can be
used to read/write data of 8-bit bytes.

Example- Byte streams are used to read or write binary data.

Benefits of Byte Stream


 Byte stream provides a convenient way to handle the input and output of
bytes. If your file is too large, byte stream handles data in chunks rather than
having the entire data altogether in the memory.
 They are useful when we want to read/write binary data.

Benefits of Character Stream


 Character stream provides convenient means to handle character-based
inputs and outputs.
 Since they use Unicode, Character streams can be
internationalized. Internationalization is the process of preparing an
application that supports linguistic, regional, cultural or political-specific
data.
 In some cases, character streams are more efficient than byte streams
especially when the file contains characters.
 Character streams automatically translate the internal format of the file (the
content of the file) to and from the local character set without extra effort by
the programmer.
 In short, character streams make it easy to write programs that are not
dependent upon a specific character encoding, which becomes easy to
internationalize.

Note:

 The original version of Java(Java 1.0) did not include character streams.
Thus, earlier all I/O was Byte Oriented. Character streams were added
in Java 1.1.
 Names of byte stream classes end with InputStream/OutputStream while the
names of character stream classes end with Reader/Writer.
 It is recommended to close the stream when it is no longer in use. This is to
ensure that the streams shouldn't be affected if any error occurs.
 The above codes may not run in online compilers as the source files may not
exist.

Conclusion
 The stream method helps to sequentially access a file.
 There are 2 Streams in Java- Byte Stream and Character Stream.
 Byte streams are used to perform input and output of 8-bit bytes.
 Byte streams are useful when we want to read/write binary data.
 Character stream is used to perform input and output operations of 16-bit
Unicode.
 Character streams are used to read/write characters.
 Byte Streams and Character Streams have a three phase mechanism which
includes Split, Apply and Combine.
 FileInputStream and FileOutputStream are common classes to read/write
data using byte streams.
 FileReader and FileWriter are commonly used to read/write data using
character streams.
Challenge Time!
Create a File in Java
. Overview
File class in Java is an abstract representation of file and directory path names. It
contains variables and methods required for the creation, reading, updating, and
deletion of files and directories. File, Files, and FileOutputStream are the classes
that provide methods to create a file(s) or directory(s) in java. These classes
provide necessary methods for working with path names, file names, creating a
new file(s) and directory(s), etc. File and FileOutputStream class belong
to java's io package, whereas Files class belongs to java's nio package.

Introduction
Imagine you have written a java program that fetches data from some remote
server, but you cannot read the data instantly and decide that you want to read that
data at some other suitable time. So basically you want your java program to store
that data as soon as it fetches onto your hard disk. How will you store data on a
physical storage device like a hard disk from your Java program?

File class in Java is used whenever a user wants to store new data, read and/or
modify old data, append new data, create new folders, etc on to some storage
device. It is a concrete class which provides methods for creating, reading,
modifying, and deleting files and folders.

"There are mainly three ways of creating a file through code in Java using JDK
libraries:

1. Using the createFile() method of the Files class present in


the [Link] package.
2. Using the createNewFile() method of the File class present in
the [Link] package.
3. Using the FileOutputStream(String fileName, boolean append) constructor
of the FileOutputStream class present in the [Link] package.

where, io stands for input-output and, nio stands for non-blocking input-output.

File(s) can also be created in Java using some external libraries like Google
Guava, and Apache Commons IO library.

Ways to Create File in Java


[Link]() Method
"The [Link]() method is used to create a new file. It is a method of the
Files class, which belongs to the [Link] package. This method creates a new
file if a file with the same name does not already exist. However, if the file already
exists, an exception named FileAlreadyExistsException is thrown.

Files class belongs to [Link] package.

Interesting Fact:
[Link] package is buffer oriented.

Syntax:
public static Path createFile(Path path, FileAttribute<?>... attributes) throws
IOException

Creates a new and empty file if the file does not already exist, otherwise, it throws
an exception if the file already exists. The attributes parameter is optional file
attributes to set atomically when creating the file. Each attribute is identified using
its name. If more than one attribute of the same name is present in the array then all
occurrences will be ignored except the last occurrence.

Parameters:
path - path to the file. attributes - an optional list of file attributes to set
automically during file creation. A FileAttribute is an object that encapsulates the
value of a file attribute that can be set atomically like File permissions can be set in
a file attribute. e.g,
Set<PosixFilePermission> perms =
[Link]("rw-------");
FileAttribute<Set<PosixFilePermission>> attr =
[Link](perms);`

Returns:
The created file
Throws:
UnsupportedOperationException - if the FileAttribute array contains an attribute
that cannot be set atomically when creating the file

FileAlreadyExistsException - if a file of that name already exists (optional


specific exception)

IOException - if an I/O error occurs or the parent directory does not exist

SecurityException - In the case of the default provider, and a security manager is


installed, the checkWrite method is invoked to check write access to the new file.

Example:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FileCreator {

public static void main(String... args) throws IOException


{
[Link]("Using createFile() method of Files
class: ");
Path path = [Link]("[Link]");
try {
[Link](path);
[Link]("File Created: " + path);
} catch (FileAlreadyExistsException e) {
[Link]("File already exists at Path: " +
path);
}
}
}

Output(s):
Using createFile() method of Files class:
File already exists at Path: [Link]

Explanation:

As we already discussed that [Link]() method requires a Path class object


as an argument, so we have created a path object of Path class, for the file path
given as "[Link]". As we have not used anything before [Link], this
means that the compiler will look for the file in the current working directory itself,
where the current program is saved.

The file gets created when there does not exist a file previously, but if the file
already exists in the directory, then a FileAlreadyExistsException will be thrown,
which is handled by a print statement, to notify the user.

"The createNewFile() method belongs to the File class in Java's [Link] package. It
is used to create a new, empty file. The method does not accept any arguments. If
the file does not already exist, it will be automatically created.

The File class is stream-oriented, which means it provides methods for reading or
writing streams of bytes. However, the createNewFile() method itself does not
perform any stream-oriented operations. It simply creates an empty file on the file
system.

When working with stream-oriented operations, such as reading bytes from a


stream, you can read one or more bytes at a time, but they are not inherently
cached anywhere. To enable flexibility in moving back and forth in the data read
from a stream, you can cache the data in a buffer first. However, the caching
process is not directly related to the createNewFile() method itself.

Interesting Fact:
[Link] package is stream oriented.

Syntax:
public boolean createNewFile() throws IOException Atomically creates a new
and empty file if and only if a file with the same name does not yet exist. The
check for the existence of the file and the creation of the file if it does not exist are
a single operation that is atomic with respect to all other filesystem activities that
might affect the file.
Parameters:
None

Returns:
true - if the file does not exist and was successfully created; false - if the file
already exists;

Throws:
IOException - If an I/O error is occurred SecurityException - If a security
manager exists and the method [Link]([Link])
denies the write access to the file

Example:
import [Link];
import [Link];

public class FileCreator {

public static void main(String... args) {


File file = new File("[Link]");
try {
[Link]("Using createNewFile() method of
File class: ");
boolean isFileCreated = [Link]();
if (isFileCreated) {
[Link]("File created at Path: " +
[Link]());
} else {
[Link](
"File already exist at Path: " +
[Link]()
);
}
} catch (IOException e) {
[Link](e);
}
}
}

Output(s):
Using createNewFile() method of File class:
File created at Path:
/Users/manasbhardwaj/Desktop/Ganymede/Daily/[Link]
Explanation:

Here, an object of the File class is created, which has the


function createNewFile(). This function returns a value true if the file is created
successfully, else it will return a false if the file already exists. Respective print
statements are written for the user’s convenience, in order to get the actual status.

[Link]() function also throws an IOException, which is handled using


the try-catch block.

FileOutputStream() Method
A FileOutputStream is an output stream used for writing data to
a File or FileDescriptor. It is part of Java's [Link] package and provides support for
file-related operations. The class offers different constructors to create instances
for writing to files. When creating a new instance, if the file does not exist, a new
file is created. However, if there are security restrictions or insufficient
permissions, a FileNotFoundException is thrown.

Important Fact:
FileOutputStream is primarily designed for writing streams of raw bytes, such as
image data. For writing streams of characters, it is recommended to use
the FileWriter class.

Syntax:
 FileOutputStream(File file): Creates a file output stream to write to the file
represented by the given File object.
 FileOutputStream(File file, boolean append): Creates a file output stream to
write to the file represented by the given File object in append mode
if append is set to true.
 FileOutputStream(FileDescriptor fdObj): Creates a file output stream to
write to the specified file descriptor, which represents an existing connection
to an actual file in the file system.
 FileOutputStream(String fileName): Creates a file output stream to write to
the file represented by the given fileName string.
 FileOutputStream(String fileName, boolean append): Creates a file output
stream to write to the file represented by the given fileName string in
append mode if append is set to true.

Example:
import [Link];
import [Link];
import [Link];
import [Link].*;

public class FileCreator {

public static void main(String... args) throws IOException


{
[Link](
"Using FileOutputStream(String name, boolean append)
constructor of FileOutputStream class: "
);
try {
String fileName = "[Link]";
FileOutputStream fosObj = new
FileOutputStream(fileName, true);
String text = "Just do it...";
byte[] textDataInBytes = [Link]();
[Link](textDataInBytes);
[Link]();
[Link]("File Saved: " + fileName);
} catch (FileNotFoundException e) {
[Link](e);
}
}
}

Output(s):
Using FileOutputStream(String name, boolean append)
constructor of FileOutputStream class:
File Saved: [Link]

Explanation:

Here, we are creating a FileOutputStream class object using a file name and the
append mode set to true, which means the new data will be added to the file after
the end text. We have taken a sample text in the string, and after converting it to
raw bytes, written it to the file output stream, and closed the stream at the end after
all work is done. If the file does not exist, then a new file is created. If the file is
not able to open due to security reasons, then FileNotFoundException is thrown
which is handled using the try-catch block.

IO vs NIO Package
The provided comparison between the IO and NIO packages accurately highlights
the key differences:
IO NIO
Represents non-blocking Input/Output
Represents blocking Input/Output operations.
operations.
Stream-oriented: Read one or more bytes at a Buffer-oriented: Data is read into a buffer,
time from a stream. The processing of the allowing for more flexible manipulation.
data read is up to the developer. The bytes Data is cached in the buffer, enabling
are not cached, limiting the ability to move movement back and forth within the data
back and forth within the data. during processing.
Does not inherently provide the flexibility to Provides flexibility to move back and
move back and forth within the data read forth within the data as it is cached in a
from a stream due to the lack of caching. buffer, allowing for efficient processing.

Conclusion:
 There are 3 methods to create a file in Java: Using [Link]()
method, Using [Link]() method, and, Using
FileOutputStream class Constructor
 Files class belong to [Link] package, whereas File and FileOutputStream
classes belong to java's io package
 java's nio package is buffer-oriented and java's io package is stream-
oriented.
 FileOutputStream is an output stream for writing data to a File or to a
FileDescriptor.
 [Link]() is stream-oriented and creates a new and empty file
automatically if it does not yet exist.
 [Link]() is buffer-oriented and thus gives more flexibility to move
back and forth in the data as the data is cached in the buffer first and
processed afterward, as compared to stream-oriented methods.

Getting File Information Using Java IO streams

The Java programming language includes a lot of APIs that help developers to do
more efficient coding. One of them is Java IO API which is designed to read and
write data (input and output). For example, read data from a file or over the
network and then write a response back over the network.

Introduction to Java IO Streams


The Java IO API is found in the [Link] package. The Java IO package focuses
mainly on input and output to files, network streams, internal memory buffers, etc.
On the other hand, it lacks classes for opening network sockets, which are required
for network communication. We need to use the Java Networking API for this
purpose.
The Java IO package provides classes that include methods that are used to obtain
metadata of a file. The definition of metadata is "data about other data". With a file
system, the data is contained in its files and directories, and the metadata tracks
information about each of these objects. In this tutorial, we are going to learn about
various ways to determine the size of a file in Java.

File size is a measure of how much data it contains or how much storage it usually
takes. The size of a file is usually measured in bytes. In Java, the following classes
will help us to get file size:

 Java get file size using File class


 Get file size in java using FileChannel class
 Java get file size using Apache Commons IO FileUtils class

Takeaway:

 To speed up I/O operations, Java uses the concept of a stream.


 All classes required for input and output operations are included in the
[Link] package except the one for opening network sockets.

Java Getting File Size Using File Class


The Java File class is an abstract representation of file and directory pathnames. It
is found in the java. io package. This class contains various methods which can be
used to manipulate the files like creating new files and directories, searching and
deleting files, enlisting the contents of a directory, as well as determining the
attributes of files and directories. This is the oldest API to find out the size of a file
in Java.

The File class in java contains a length() method that returns the size of the file in
bytes. To use this method, we first need to create an object of the File class by
calling the File(String pathname) constructor. This constructor creates a new File
instance by converting the given pathname string into an abstract pathname.

An abstract pathname consists of an optional prefix string, such as disk drive


specifiers, “/” for Unix, or “\” for Windows, and a sequence of zero or more string
names.

The prefix string is platform-dependent. The last name in the abstract pathname
represents a file or directory. All other names represent directories.

For example, "c:\data\[Link]"


File file = new File("c:\\data\\[Link]"); //pass the
pathname as an argument
Now we can apply the File class length() method to the File object. It will return
the length, in bytes, of the file denoted by this abstract pathname, or 0L if the file
does not exist. The return value is unspecified if this pathname denotes a directory.
So, we need to make sure the file exists and isn't a directory before invoking this
java method to determine file size.

Here is the input


file:

A simple java program to determine file size using the File class is shown below:
import [Link];

class javaFileClassExample {

public static void printFileSize(File file) {


//check if the file exists or not
if ([Link]()) {
// size of a file (in bytes)
long bytes = [Link]();

// print the file size


[Link](bytes + " bytes");
[Link](bytes / 1024.0 + " kb");
} else {
// if the file doesn't exist
[Link]("File does not exist!");
}

public static void main(String args[]) {


String pathName = "C:\\Users\\SC\\Desktop\\[Link]";

// Create the File instance with pathName


File file = new File(pathName);

printFileSize(file);
}
}

Output:
6308 bytes
6.16015625 kb

Explanation: Since the file exists, it will return the file size in bytes, else it would
have return the “File does not exist!” statement.

Takeaway:

 If the pathname argument is null in File(String pathname), it will


throw NullPointerException.
 Even if the file does not exist, it won't throw an exception, it will return 0L.

Get File Size In Java Using FileChannel Class


The Java FileChannel class is a channel that is connected to a file by which we
can read data from a file and write data to a file or access file metadata. It is found
in [Link] package (NIO stands for non-blocking I/O) which is a collection of
Java programming language APIs that offer features for intensive I/O operations.

File channels are safe for use by multiple concurrent threads, making Java NIO
more efficient than Java IO. However, only one operation that involves updating a
channel's position or changing its file size is allowed at a time. If other threads are
performing a similar operation, it will block them until the previous operation is
completed.

Note: Although FileChannel is a part of the [Link] package, its operations cannot
be set into non-blocking mode, it always runs in blocking mode.

Also, we can't create objects of the FileChannel class directly, we need to create
them by invoking the open() method defined by this class. This method opens or
creates a file, returning a file channel to access the file. After creating a
FileChannel instance we can call the size() method which will return the current
size of this channel's file, measured in bytes.

Here is the input file we need to parse −

Hello World in Java!

A simple java program to determine file size using the FileChannel class is shown
below.
import [Link];
import [Link];
import [Link];
import [Link];

class javaFileChannelClassExample {
public static void printFileSize(String fileName) {
// converts the path string to a path
Path filePath = [Link](fileName);

// declaring an object of FileChannel type


FileChannel fileChannel;
try {
// pass the path to open the file
fileChannel = [Link](filePath);

// print the file size (in bytes)


long fileSize = [Link]();
[Link]("Size of the file is " +
fileSize + " bytes");

// close the channel


[Link]();

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

public static void main(String args[]) {


// path of the file in string format
String fileName = "C:\\Users\\SC\\Desktop\\[Link]";
printFileSize(fileName);
}
}

Output:
Size of the file is 20 bytes

Explanation: Since the file exists, it will return the file size in bytes, else it would
have thrown the [Link] error.

Takeaway:

 We can’t create objects of FileChannel class directly, we have to create it by


invoking the open() method.
 FileChannel is thread-safe but allows only one operation at a time that
involves the channel's position or changing its file's size, blocking other
similar operations.

Java Getting File Size Using Apache Commons IO


FileUtils Class
The Java FileUtils are general file manipulation utilities. This class is found in the
[Link] package. It includes methods to perform various
operations like writing to a file, reading from a file, making directories, copying
and deleting files and directories, etc.

The Java FileUtils class provides the sizeOf() method that returns the size of the
file in bytes. Firstly, we need to create a File instance and then pass it to
the sizeOf() method. It will return the size of the specified file or directory. If the
provided File is a regular file, then the file's length is returned. If the argument is a
directory, then the size of the directory is calculated recursively.

Note that overflow is not detected, and the return value may be negative if
overflow occurs. We can use sizeOfAsBigInteger(File) for an alternative method
that does not overflow.

Here is the input file we need to parse −

Hello World in Java!

canonical_url: [Link]
size/ title: How to get Java File Size - Scaler Topics
description: This article explains Java IO streams in brief
& different ways to get java file size, along with java
programs & various classes such as File, FileChannel, and
FileUtils. author: Soma Chandra category: Java
amphtml: [Link]
p/ publish_date: 2022-04-18
The Java programming language includes a lot of APIs that help developers to do
more efficient coding. One of them is Java IO API which is designed to read and
write data (input and output). For example, read data from a file or over the
network and then write a response back over the network.
Scope
 This article briefly explains Java IO streams and the different ways to get
file size, along with java programs.
 We also learn about various classes such as File, FileChannel, and FileUtils.

Introduction to Java IO Streams


The Java IO API is found in the [Link] package. The Java IO package focuses
mainly on input and output to files, network streams, internal memory buffers, etc.
However, it lacks classes for opening network sockets, which are required for
network communication. We need to use the Java Networking API for this
purpose.

The Java IO package provides classes that include methods used to obtain a file's
metadata. The definition of metadata is "data about other data". With a file system,
the data is contained in its files and directories, and the metadata tracks information
about each of these objects. In this tutorial, we will learn about various ways to
determine the size of a file in Java.

File size measures how much data it contains or how much storage it usually takes.
The size of a file is usually measured in bytes. In Java, the following classes will
help us to get file size:

 Java get file size using the File class


 Get file size in java using the FileChannel class
 Java get file size using Apache Commons IO FileUtils class

Takeaway:

 To speed up I/O operations, Java uses the concept of a stream.


 All classes required for input and output operations are included in the
[Link] package except for opening network sockets.

Java Getting File Size Using File Class


The Java File class is an abstract representation of file and directory pathnames. It
is found in the [Link] package. This class contains various methods for
manipulating files, such as creating new files and directories, searching and
deleting files, enlisting the contents of a directory, and determining the attributes of
files and directories. This is the oldest API for finding out the size of a file in Java.

The File class in java contains a length() method that returns the file size in bytes.
To use this method, we first need to create an object of the File class by calling
the File(String pathname) constructor. This constructor creates a new File
instance by converting the given pathname string into an abstract pathname.

An abstract pathname consists of an optional prefix string, such as disk drive


specifiers, “/” for Unix or “\” for Windows, and a sequence of zero or more string
names.

The prefix string is platform-dependent. The last name in the abstract pathname
represents a file or directory. All other names represent directories.

For example, "c:\data\[Link]"


File file = new File("c:\\data\\[Link]"); //pass the
pathname as an argument

Now, we can apply the File class length() method to the File object. It will return
the file's length, in bytes, denoted by this abstract pathname, or 0L if the file does
not exist. The return value is unspecified if this pathname denotes a directory. So,
we need to ensure the file exists and isn't a directory before using this Java method
to determine file size.

Here is the input


file:

A simple java program to determine file size using the File class is shown below:
import [Link];

class javaFileClassExample {

public static void printFileSize(File file) {


//check if the file exists or not
if ([Link]()) {
// size of a file (in bytes)
long bytes = [Link]();

//Print the file size


[Link](bytes + " bytes");
[Link](bytes / 1024.0 + " kb");
} else {
// if the file doesn't exist
[Link]("File does not exist!");
}

public static void main(String args[]) {


String pathName = "C:\\Users\\SC\\Desktop\\[Link]";

// Create the File instance with pathName


File file = new File(pathName);

printFileSize(file);
}

Output:
6308 bytes
6.16015625 kb

Explanation: Since the file exists, it will return its size in bytes; otherwise, it
would have returned the “File does not exist!” statement.

Takeaway:

 If the pathname argument is null in File(String pathname), it will


throw NullPointerException.
 Even if the file does not exist, it won't throw an exception; it will return 0L.

Get File Size In Java Using FileChannel Class


The Java FileChannel class is a channel that is connected to a file by which we
can read data from a file and write data to a file or access file metadata. It is found
in [Link] package (NIO stands for non-blocking I/O), a collection of Java
programming language APIs offering features for intensive I/O operations.

File channels are safe for multiple concurrent threads, making Java NIO more
efficient than Java IO. However, only one operation that involves updating a
channel's position or changing its file size is allowed at a time. If other threads
perform a similar operation, it will block them until the previous operation is
completed.
Note: Although FileChannel is part of the [Link] package, its operations cannot
be set to non-blocking mode; it always runs in blocking mode.

Also, we can't create objects of the FileChannel class directly; we need to invoke
the open() method defined by this class. This method opens or creates a file,
returning a file channel to access the file. After creating a FileChannel instance, we
can call the size() method, which will return the current size of this channel's file,
measured in bytes.

Here is the input file we need to parse −

Hello World in Java!

A simple java program to determine file size using the FileChannel class is shown
below.
import [Link];
import [Link];
import [Link];
import [Link];

class javaFileChannelClassExample {
public static void printFileSize(String fileName) {
// converts the path string to a path
Path filePath = [Link](fileName);

// declaring an object of FileChannel type


FileChannel fileChannel;
try {
//Pass the path to open the file
fileChannel = [Link](filePath);

//Print the file size (in bytes)


long fileSize = [Link]();
[Link]("Size of the file is " +
fileSize + " bytes");

//Close the channel


[Link]();

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

public static void main(String args[]) {


// path of the file in string format
String fileName = "C:\\Users\\SC\\Desktop\\[Link]";
printFileSize(fileName);
}
}

Output:
Size of the file is 20 bytes

Explanation: Since the file exists, it will return the file size in bytes; otherwise, it
would have thrown the [Link] error.

Takeaway:

 We can’t create objects of the FileChannel class directly; we have to create


them by invoking the open() method.
 FileChannel is thread-safe but allows only one operation at a time
involving the channel's position or changing its file's size, blocking similar
operations.

Java Getting File Size Using Apache Commons IO


FileUtils Class
The Java FileUtils are general file manipulation utilities. This class is found in the
[Link] package. It includes methods to perform various
operations like writing to a file, reading from a file, making directories, copying
and deleting files and directories, etc.

The Java FileUtils class provides the sizeOf() method, which returns the file's size
in bytes. First, we need to create a File instance and then pass it to
the sizeOf() method. It will return the size of the specified file or directory. If the
provided File is a regular file, then the file's length is returned. If the argument is a
directory, then the directory size is calculated recursively.

Overflow is not detected, and the return value may be negative if overflow occurs.
We can use sizeOfAsBigInteger(File) for an alternative method that does not
overflow.

Here is the input file we need to parse −

Hello World in Java!

A simple java program to determine file size using the FileUtils class is shown
below.
import [Link];
import [Link];
import [Link];

public class javaFileUtilsClassExample {


public static void printFileSize(String fileName) {
// try-catch block if an exception occurs
try {
// creates a File instance with fileName
File file = new File(fileName);

//Print the file size (in bytes)


long fileSize = [Link](file);
[Link]("Size of the file is " +
fileSize + " bytes");
} catch (Exception e) {
[Link]();
}

public static void main(String[] args) throws IOException


{
// path of the file in string format
String fileName = "C:\\Users\\SC\\Desktop\\[Link]";

printFileSize(fileName);
}
}

Output:
Size of the file is 20 bytes

Explanation: Since the file exists, it returns its size in bytes; otherwise, it would
have thrown an exception.

Takeaway:

 The sizeOf() method will return the size of the specified file in bytes.
 If the file is null, it will throw NullPointerException, and if the file does not
exist, it will throw IllegalArgumentException,

Conclusion
 The [Link] package provides for system input and output through data
streams, serialization, and the file system.
 Java provides various classes to determine the file size,
i.e. File, FileChannel, and FileUtils class.
 The File class is found in the [Link] package and provides
a length() method to get file size.
 The FileChannel class is found in the [Link] package and
provides size() method to determine the file size.
 FileChannel is thread-safe, making Java NIO more efficient than Java IO.
 The operations of FileChannel are blocking and can’t be set into non-
blocking mode.
 The Java FileUtils class is found in the [Link] package and
provides the sizeOf() method to determine the file size.
import [Link];
import [Link];

import [Link];

public class javaFileUtilsClassExample {


public static void printFileSize(String fileName) {
// try - catch block if exception occurs
try {
// creates a File instance with fileName
File file = new File(fileName);

// print the file size (in bytes)


long fileSize = [Link](file);
[Link]("Size of the file is " +
fileSize + " bytes");
} catch (Exception e) {
[Link]();
}

public static void main(String[] args) throws IOException


{
// path of the file in string format
String fileName = "C:\\Users\\SC\\Desktop\\[Link]";

printFileSize(fileName);
}
}

Output:

Size of the file is 20 bytes

Explanation: Since the file exists, it returns the file size in bytes, else it would have thrown
an exception.

Takeaway:
 The sizeOf() method will return the size of the specified file in bytes.
 If the file is null, it will throw NullPointerException, and if the file does not exist, it
will throw IllegalArgumentException, :::

Conclusion
 The [Link] package provides for system input and output through data
streams, serialization, and the file system.
 Java provides various classes to determine the file size
i.e. File, FileChannel, and FileUtils class.
 The File class is found in the [Link] package and provides
a length() method to get file size.
 The FileChannel class is found in the [Link] package and
provides size() method to determine the file size.
 FileChannel is thread-safe, making Java NIO more efficient than Java IO.
 The operations of FileChannel are blocking and can’t be set into non-
blocking mode.
 The Java FileUtils class is found in [Link] package and
provides sizeOf() method to determine the file size.
JAVA IO - Write to a File using Java IO streams

In Java, many techniques can be used to write into a


file. [Link], [Link], [Link], [Link]
m, etc., are some of the classes in Java that help to write in a file. By creating an
object of the above-mentioned classes, we can access the methods of that class that
are used to write into a file. All the above-mentioned classes are included inside a
single package called [Link]. The [Link] package provides various input and
output streams that enable us to read data from the file and write data into the file.

Introduction
In real-world applications, people run many programs and get their outputs.
Sometimes, storing the result of the executed program is necessary, as the output
may be needed for later use. So, the output displayed on the screen must be stored
in files. In Java, the [Link] package provides a number of classes that will help
users store the result in the file. This article will discuss a few methods for helping
users store data in a file using the [Link] package.

Methods to write a file in Java


1. Using FileWriter Class
Often, we need to write a small amount of content into a file. For that purpose, we
use the FileWriter class. To implement this class, we need to import
the FileWriter class. While writing the data into the file, there may be several
exceptions. To throw the exceptions, we will import the IOException class.

Steps for writing into a file using FileWriter class:

1. First, create an instance of the FileWriter class and pass the file's relative path
into it.

Syntax

FileWriter f = new FileWriter(“[Link]”)

2. Use the newly created instance and pass the string parameter by
using .write() method. (We can pass int, char, char array and string to this method)

Syntax

[Link](string)

3. Lastly, close the file using the .close() method. By closing this file, exceptions
will not be generated.

Syntax

[Link]()

Perform all the operations using a try-catch block to print all the exceptions. As we
are using the IOexception class in our code, exceptions need to be thrown out. We
use this try-catch block to throw all the exceptions and test the code for errors.

Here's an example of writing into a file using the FileWriter class. In the
following example, we will create a string and write that string into the "[Link]"
file. For that, we will create an object of the FileWriter class and pass the relative
path of the "[Link]" file in the object. Using the .write() method provided by
FileWrite class, we will write the content of the string into the file. Finally, we
close the file using .close() method.

Code
// importing FileWriter class and IOException class
import [Link];
import [Link];

class Scaler{
public static void main(String[] args) {
// a short text
String content = "Hello Welcome to Scaler!";
try{

// creating an instance of FileWrite class


FileWriter f = new FileWriter("[Link]");

// using write method to write the content into


the file
[Link](content);

// closing a file
[Link]();

// displaying a message after successfully


writing into a file
[Link]("Content is successfully added
into the [Link] file.");
}
catch(IOException e){
// displaying the exception
[Link](e);
}
}
}

Output
Content is successfully added into the [Link] file.

Explanation

The “[Link]” file will contain the following text:

Hello Welcome to Scaler!

Also, the terminal will display the following message:

Content is successfully added into the [Link] file.

2. Using writeString() method


This method is the same as FileWriter class because it is also used to write into a
file for small text. But the writeString() method takes four parameters. Among
the four parameters, first two are mandatory. The first two mandatory parameters
are relative file path and the text that we need to write into the file. The other two
parameters are charset and open option. A sequence of characters (string) is
encoded into bytes using a specified charset, and the open option specifies how the
file is created or opened. We have CREATE, OPEN and TRUNCATE_EXISTING
options available. In other words, it opens the file for writing, creating the file if
the file doesn't exist, or initially truncating(making short) an existing regular-file to
a size of 0. We need to import three classes to implement this
method: IOException for throwing an exception, Files class for writing into the
file, and Path class for getting the path of the file(the file in which the user is
going to write).

Steps for writing into a file using writeString class:

1. Get the relative path of the file the user wants to write using the Path class.

Syntax

Path p = [Link](“[Link]”)

2. Use the writeString() method of the Files class and pass two parameters: the
path of the file and text.

Syntax

[Link](p, text)

You can use the [Link](p) method to read the file's content from
the Files class.

Here's an example of writing into the file using FileOutputStream class. In the
following example, first, we will create a string that needs to be written into the
file. Furthermore, we will get the path of the file in which string is to be written
using the Path class. We will write the string into the file using
the writeString() method. To check whether the string is written into the file, we
will use the readString() method to read the file's contents.

Code
// importing Files, Path and IOException class
import [Link];
import [Link];
import [Link];

class Scaler{
public static void main(String[] args)
throws IOException {
// a short text
String content = "Hello Welcome to Scaler!";

// getting the file path in which we are writing


Path pathForFile = [Link]("[Link]");
// writing into the file using writeString method
[Link](pathForFile, content);

// reading the file


String fileText = [Link](pathForFile);

// printing the contents of the file


[Link](fileText);
}
}

Output
Hello, Welcome to Scaler!

Explanation

The “[Link]” file will contain the following text:

Hello Welcome to Scaler!

Also, the terminal will display the contents of the file:

Hello Welcome to Scaler!

3. Using FileOutputStream class


FileOutputStream class is used to write raw data stream into the file. Normally,
we can write text into the file, but we can also write binary data into the file by
using the .write() method provided by this class. We can only write byte-
oriented and character-oriented data into the file by using FileOutputStream
class. To implement this class, we need to import FileOutputStream class.

Steps for writing into a file using FileOutputStream class:

1. First, create an object of FileOutputStream class. It takes an argument, i.e., a


relative path of the file.

Syntax

FileOutputStream f = new FileOutputStream(“[Link]”)

2. Convert the string(that is to be written into the file) into bytes and store it in the
byte array.

Syntax
byte[] bytes_array = [Link]()

3. Now, use the .write() method of FileOutputStream and pass the byte array into
it.

Syntax

[Link](bytes_array)

4. The Final step is to close the file using the .close() method. This is necessary to
prevent exceptions.

Syntax

[Link]()

To throw exceptions, implement all the above steps in a try-catch block and the
final statement.

Here's an example of writing into the file using the FileOutputStream class. In the
following example, first, we will create a string that needs to be written into the
file. Then, we will create an object of FileOutputStream. Later, we will convert the
string into a byte array, and using the .write() function, we will write the byte array
into the output stream that we created. Finally, we will close the file using
the .close() method.

Code
// importing FileOutputStream and IOException class
import [Link];
import [Link];

class Scaler{
public static void main(String[] args)
throws IOException {
// a short text
String content = "Hello Join Scaler Today!";

// creating an instance of FileOutputStream


FileOutputStream f = null;

try{
// creating an object of FileOutputStream
f = new FileOutputStream("[Link]");

// converting the string to bytes array


byte[] strToBytes = [Link]();
//writing into a file
[Link](strToBytes);

// printing successful message


[Link]("Content is successfully added
into the [Link] file.");

// closing the FileOutputStream


[Link]();
}
catch (IOException e){
// throwing out error
[Link](e);
}
}
}

Output
Content is successfully added into the [Link] file.

Explanation

The “[Link]” file will contain the following text:

Hello Join Scaler Today!

Also, the terminal will display the contents of the file:

Content is successfully added into the [Link] file.

4. Using BufferedWriter class


The .write() method of BufferedWriter class in Java is used to write the text in a
character-output stream. Buffering characters efficiently write strings, single
characters, and arrays. In the BufferedWriter class, users can also define their own
buffer size, although it has a default buffer size that is large enough for many
purposes. In order to implement this class, we need to import
the BufferedWriter class and the FileWriter class. BufferedWriter class needs a
character output stream as a parameter, so in order to create a character output
stream, we require the FileWriter class.

Steps for writing into a file using BufferedWriter class:

1. First, create an object of the BufferefWriter class; get an output stream using the
FileWriter class.

Syntax
BufferedWriter f = new BufferedWriter(new FileWriter(“[Link]”))

2. Now write the content(string) into the buffer that we have created using
the .write(text) function. However, we can write integers, characters, and arrays of
characters into the file instead of using the string.

Syntax

[Link](content)

3. Lastly, close the BufferedWriter object using .close() function.

Syntax

[Link]()

Here's an example of writing into the file using the BufferedWriter class. In the
following example, first, we will create a string that needs to be written into the
file. As the BufferedWriter class needs an output stream as a parameter, we pass
the output stream of the FileWriter class by creating its object. Later, we write into
the BufferedWriter object using the .write() method. Finally, we close the file
using the .close() method.

Code
// importing FileOutputStream and IOException class
import [Link];
import [Link];
import [Link];

class Scaler{
public static void main(String[] args)
throws IOException {
// a short text
String content = "Hello welcome to Scaler!";

try{
// creating an object of BufferedWriter class
BufferedWriter f = new BufferedWriter(new
FileWriter("[Link]"));

//writing into a buffer


[Link](content);

// printing successful message


[Link]("Content is successfully added
into the [Link] file.");
// closing the FileOutputStream
[Link]();
}
catch (IOException e){
// throwing out error
[Link](e);
}
}
}

Output
Content is successfully added into the [Link] file.

Explanation

The “[Link]” file will contain the following text:

Hello welcome to Scaler!

Also, the terminal will display the contents of the file:

Content is successfully added into the [Link] file.

5. Using FileChannel class


FileChannel class in Java is used for reading, writing, mapping, and manipulating
a file. In this section, we will discuss the .write() method that is used to write into
the file. An “open for writing” instance is required to implement this class.
FileChannel class is safe for use by multiple concurrent threads (concurrency is
the ability to run several programs and threads in parallel). By invoking one of the
open methods, a file channel is created. We can also obtain a file channel by
invoking the getChannel() method of an existing FileOutputStream object, which
returns a file channel that is connected to the same file. I will discuss one of the
methods to write into a file using FileChannel class. We need to
import FileOutputStream class, ByteBuffer class, and FileChannel class.

Steps for writing into a file using FileChannel class:

1. First, we will create an object of FileOutputStream. We pass the relative path of


the file as an argument.

Syntax

FileOutputStream f = new FileOutputStream("[Link]")


2. Now, we will obtain a channel of an opened output stream using
the getChannel() method. As the fileChannel class needs a channel of the output
stream, we need to convert an output stream into a channel to implement
the .write() method.

Syntax

FileChannel f_channel = [Link]()

3. Create an object of ByteBuffer and allocate some space to store the text that
needs to be written into the file. ByteBuffer provides a buffer that helps in
transferring bytes from source to destination.

Syntax

ByteBuffer bb = [Link](space)

4. Put all the bytes of data into the buffer.

Syntax

[Link]((byte) [Link](i))

5. Use the .rewind() method to set the buffer's position to zero. As the buffer's
position may have an arbitrary value at the start, we need to initialize it to zero.

Syntax

[Link]()

6. Write the bytes into the channel using the .write() method provided by
FileChannel class.

Syntax

f_channel.write(bb)

7. Lastly, close the file using the .close() method.

Syntax

f_channel.close()

Here's an example of writing into the file using FileChannel class. In the
following example, first, we will create a string that needs to be written into the
file. Then, we will create an output stream using a FileOutputStream class. The
fileChannel class requires an output stream channel to write into the file, so we get
the output stream's channel by using the .getChannel() method provided by the
FileOutputStream class. To write any text into the channel, we need to convert the
text into a buffer of bytes, so we will create a ByteBuffer of size 50 bytes(allocate
size according to your need). Put all the bytes into the channel using
the .put() method. Initialize the position of the buffer to zero by
using .rewind() method. Finally, we will write into the channel using
the .write() method and close the channel using the .close() method.

Code
// importing FileOutputStream and IOException class
import [Link];
import [Link];
import [Link];
import [Link];

class Scaler{
public static void main(String[] args)
throws IOException {
// a short text
String content = "Hello guys visit Scaler for more
awesome blogs!";

try{
// creating an object of FileOutputStream class
FileOutputStream f = new
FileOutputStream("[Link]");

// obtaining a file channel


FileChannel fChannel = [Link]();

// creating an object of bytebuffer and


allocating space of 50 bytes
ByteBuffer bb = [Link](50);

// putting each byte of string into a buffer


for(int i=0; i<[Link](); i++){
[Link]((byte) [Link](i));
}

// setting the position of buffer to zero


[Link]();

// writing into the channel


[Link](bb);

// printing successful message


[Link]("Content is successfully added
into the [Link] file.");

// closing the channel


[Link]();
}
catch (IOException e){
// throwing out error
[Link](e);
}
}
}

Output
Content is successfully added into the [Link] file.

Explanation

The “[Link]” file will contain the following text:

Hello guys visit Scaler for more awesome blogs!

Also, the terminal will display the contents of the file:

Content is successfully added into the [Link] file.

6. Using DataOutputStream class


To write primitive data types into the output stream in a portable way, we
use DataOutputStream class because it formats the data in a platform-
independent way. The data output stream is typically used by Java applications to
write data that a data input stream can later read. DataOutputStream has many
methods, such as writeInt(used to write an integer to the output stream)
and writeChar(used to write a character to an output stream). Similarly, there are
other methods like writeByte, writeBytes, writeLong, writeShort, writeBoolean. To
implement this class, we need to import DataOutputStream class and
FileOutputStream class.

Steps for writing into a file using DataOutputStream class:

1. First, create an object of FileOutputStream.

Syntax

FileOutputStream fo = new FileOutputStream("[Link]")


2. Now, create an object of DataOutputStream by passing an object of
FileOutputStream as a parameter. Here, FileInputStream provides an output stream
that is needed for the object of DataObjectStream.

Syntax

DataOutputStream dfo = new DataOutputStream(fo)

3. Write into the stream by using any of the write method


i.e., .writeInt(), .writeDouble(), .writeChar(), etc.,

4. Flush the DataOutputStream using the .flush() function. Flush forces the bytes to
be written to the underlying stream.

Syntax

[Link]()

5. Close the DataOutputStream using .close() function.

Syntax

[Link]()

To read the file's contents, use DataInputStream, as shown in the following


program.

Here's an example of writing into the file using DataOutputStream class. In the
following example, first, we will create a string that needs to be written into the
file. Furthermore, we will create an output stream using the FileOutputStream class
and provide it to the object of DataOutputStream class. Now we will perform
several methods like .writeInt(), .writeDouble(), etc. Flush the current stream using
the .flush() method. Finally, close the DataOutputStream by using .close() method.

Code
// importing FileOutputStream and IOException class
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

class Scaler{
public static void main(String[] args)
throws IOException {
// a short text
String content = "Hello guys visit Scaler for more
awesome blogs!";

try{
// creating an object of FileOutputStream class
FileOutputStream fo = new
FileOutputStream("[Link]");

// creating an object of DataOutputStream


DataOutputStream dfo = new DataOutputStream(fo);

// writing an integer value to the outputstream


[Link](55);

// writing a double value to the outputstream


[Link](152.255);

// writing a char value to the outputstream


[Link]('G');

// flushing the DataOutputStream


[Link]();

// closing the channel


[Link]();

// printing successful message


[Link]("Content is successfully added
into the [Link] file.");

// creating an object of FileInputStream class


FileInputStream fi = new
FileInputStream("[Link]");

DataInputStream dfi = new DataInputStream(fi);

// reading the integer from the input stream


[Link]("Integer value of the file:
"+[Link]());

// reading the double from the input stream


[Link]("Double value of the file:
"+[Link]());

// reading the char from the input stream


[Link]("Char value of the file:
"+[Link]());
}
catch (IOException e){
// throwing out error
[Link](e);
}
}
}

Output
Content is successfully added into the [Link] file.
Integer value of the file: 55
Double value of the file: 152.255
Char value of the file: G

Explanation

The output file will contain the following text.

0000 0037 4063 0828 f5c2 8f5c 0047

The terminal will have the following output:

Content is successfully added into the [Link] file.

Integer value of the file: 55

Double value of the file: 152.255

Char value of the file: G

Conclusion
FileWriter is the simplest way to write into a file because it provides most of the
features, like an overloaded write method that allows us to write integers, strings,
parts of strings, bytes, and others into the file. The writeString method of
the FileWriter class is used to write only specified strings into the file. It takes a
string as an argument and does not return any value.

 FileOutputStream is a byte stream that writes the data into the file in binary
format, which is exactly 8-bit.
 BufferedWriter writes the text to the character-output stream. It provides
efficient writing of arrays, strings, and single characters. FileChannel helps
write at a specific position in a file. The transfer of file data from one
channel to another is faster.
 DataOutputStream enables us to efficiently write byte, char, int, boolean

You might also like