Java Exception
Java Exception
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.
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.
Input Streams.
Output Streams.
Error Streams.
Java supports three streams that are automatically attached with the console.
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.
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.
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
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.
The method above returns the number of bytes that can be read from the input
stream.
The method above closes the current input stream and releases any associated
system resources.
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.
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.
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.
It repositions the stream to the last called mark position. The reset method does
nothing for input stream class except throwing an exception.
Examples
1. In the below example, we will use FileInputStream class to read the input
file: [Link].
Code:
import [Link].*;
class Main {
// 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
Code:
import [Link].*;
class Main {
Output:
Available bytes: 31
Scaler Topics
From InterviewBit
Code:
import [Link].*;
class Main {
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]();
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
It flushes the current output stream and forces any buffered output to be written
out.
This method writes the [Link] bytes from the specified byte array to the output
stream.
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.
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%
Some methods that are inherited from class [Link]. These methods are
used for both input stream and output stream purposes.
Examples
1. In the example below, we will use the FileOutputStream class to read the
file.
Code:
import [Link].*;
class Main {
Output:
Code:
import [Link].*;
class Main {
// declaring a f1 as BufferedOutputStream
BufferedOutputStream f2 = new BufferedOutputStream(f1);
Output:
Code:
import [Link].*;
class Main {
// 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:
Quiz Type
SCQ
100
Success Rate:35%
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?
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.
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.
Java provides many byte stream classes, but the most common ones are-
Syntax:
FileInputStream sourceStream = new
FileInputStream("path_to_file");
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.
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]");
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.
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");
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:
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.
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
IOException - if an I/O error occurs or the parent directory does not exist
Example:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Output(s):
Using createFile() method of Files class:
File already exists at Path: [Link]
Explanation:
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.
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];
Output(s):
Using createNewFile() method of File class:
File created at Path:
/Users/manasbhardwaj/Desktop/Ganymede/Daily/[Link]
Explanation:
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].*;
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.
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.
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:
Takeaway:
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.
The prefix string is platform-dependent. The last name in the abstract pathname
represents a file or directory. All other names represent directories.
A simple java program to determine file size using the File class is shown below:
import [Link];
class javaFileClassExample {
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:
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.
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);
} catch (Exception e) {
[Link]();
}
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:
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.
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.
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:
Takeaway:
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.
The prefix string is platform-dependent. The last name in the abstract pathname
represents a file or directory. All other names represent directories.
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.
A simple java program to determine file size using the File class is shown below:
import [Link];
class javaFileClassExample {
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:
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.
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);
} catch (Exception e) {
[Link]();
}
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:
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.
A simple java program to determine file size using the FileUtils class is shown
below.
import [Link];
import [Link];
import [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];
printFileSize(fileName);
}
}
Output:
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
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.
1. First, create an instance of the FileWriter class and pass the file's relative path
into it.
Syntax
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{
// closing a file
[Link]();
Output
Content is successfully added into the [Link] file.
Explanation
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!";
Output
Hello, Welcome to Scaler!
Explanation
Syntax
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!";
try{
// creating an object of FileOutputStream
f = new FileOutputStream("[Link]");
Output
Content is successfully added into the [Link] file.
Explanation
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)
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]"));
Output
Content is successfully added into the [Link] file.
Explanation
Syntax
Syntax
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)
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)
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]");
Output
Content is successfully added into the [Link] file.
Explanation
Syntax
Syntax
4. Flush the DataOutputStream using the .flush() function. Flush forces the bytes to
be written to the underlying stream.
Syntax
[Link]()
Syntax
[Link]()
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]");
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
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