Java I/O tutorial with examples
11:34:00
I have written
several tutorials on Java I/O. You can find out the links of all the tutorials
below. The tutorials are explained with the help of very basic and simple
examples so that even a beginner can learn with ease. I will continue to write more
tutorials on I/O and will add the links below.
How to create
a File in Java
In this
tutorial we will see how to create a file in Java using createNewFile()
method. This method creates an empty
file, if the file doesn’t exist at the specified location and returns true. If
the file is already present then this method returns false. It throws:
IOException
–
If an Input/Output error occurs during file creation.
SecurityException
–
If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method
denies write access to the file.
Complete code:
The below code would create a txt file named “newfile.txt” in C drive. You can
change the path in the below code in order to create the file in different
directory or in different drive.
package beginnersbook.com;
import java.io.File;
import java.io.IOException;
public class CreateFileDemo
{
public static void main( String[] args )
{
try {
File file = new File("C:\\newfile.txt");
/*If file gets created then the createNewFile()
* method would return true or if the file is
* already present it would return false
*/
boolean fvar = file.createNewFile();
if (fvar){
System.out.println("File has been created successfully");
}
else{
System.out.println("File already present at the specified location");
}
} catch (IOException e) {
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
}
createNewFile()
method. This method creates an empty
file, if the file doesn’t exist at the specified location and returns true. If
the file is already present then this method returns false. It throws:IOException
–
If an Input/Output error occurs during file creation.SecurityException
–
If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method
denies write access to the file.The below code would create a txt file named “newfile.txt” in C drive. You can change the path in the below code in order to create the file in different directory or in different drive.
How to read
file in Java – BufferedInputStream
In this
example we will see how to read a file in Java using FileInputStream
and BufferedInputStream
. Here are the detailed steps that we
have taken in the below code:
1) Created a File instance by providing the full path of the file(which we will
read) during File Object creation.
2) Passed the file instance to the FileInputStream which opens a connection to the actual
file, the file named by the File object file in the file system.
3) Passed the FileInputStream
instance to BufferedInputStream which creates a BufferedInputStream
and saves its argument, the input stream
in, for later use. An internal buffer array is created and stored in buf using
which the read operation gives good performance as the content is readily
available in the buffer.
4) Used while loop to read the file. Method available() is used for checking the end of the file
as it returns 0 when the pointer reaches to the end of the file. Read the file
content using read() method of FileInputStream
.
package beginnersbook.com;
import java.io.*;
public class ReadFileDemo {
public static void main(String[] args) {
//Specify the path of the file here
File file = new File("C://myfile.txt");
BufferedInputStream bis = null;
FileInputStream fis= null;
try
{
//FileInputStream to read the file
fis = new FileInputStream(file);
/*Passed the FileInputStream to BufferedInputStream
*For Fast read using the buffer array.*/
bis = new BufferedInputStream(fis);
/*available() method of BufferedInputStream
* returns 0 when there are no more bytes
* present in the file to be read*/
while( bis.available() > 0 ){
System.out.print((char)bis.read());
}
}catch(FileNotFoundException fnfe)
{
System.out.println("The specified file not found" + fnfe);
}
catch(IOException ioe)
{
System.out.println("I/O Exception: " + ioe);
}
finally
{
try{
if(bis != null && fis!=null)
{
fis.close();
bis.close();
}
}catch(IOException ioe)
{
System.out.println("Error in InputStream close(): " + ioe);
}
}
}
}
FileInputStream
and BufferedInputStream
. Here are the detailed steps that we
have taken in the below code:1) Created a File instance by providing the full path of the file(which we will read) during File Object creation.
2) Passed the file instance to the FileInputStream which opens a connection to the actual file, the file named by the File object file in the file system.
3) Passed the
FileInputStream
instance to BufferedInputStream which creates a BufferedInputStream
and saves its argument, the input stream
in, for later use. An internal buffer array is created and stored in buf using
which the read operation gives good performance as the content is readily
available in the buffer.4) Used while loop to read the file. Method available() is used for checking the end of the file as it returns 0 when the pointer reaches to the end of the file. Read the file content using read() method of
FileInputStream
.
How to read
file in Java using BufferedReader
In this
tutorial we will see two ways to read a file using BufferedReader.
Method 1: Using readLine() method of BufferedReader
class.
public String readLine() throws IOException
It reads a line
of text.
Method 2: Using read() method
public int read() throws IOException
It reads a
character of text. Since it returns an integer value, it needs to be explicitly
cast as char
for reading the content of file.
Complete example
Here I have two
txt files myfile.txt
and myfile2.txt
. In order to demonstrate both the ways to read file. I’m
reading first file using readLine()
method while the second file is being read using read()
method.
package beginnersbook.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileDemo {
public static void main(String[] args) {
BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader("B:\\myfile.txt"));
//One way of reading the file
System.out.println("Reading the file using readLine() method:");
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();
}
br2 = new BufferedReader(new FileReader("B:\\myfile2.txt"));
//Second way of reading the file
System.out.println("Reading the file using read() method:");
int num=0;
char ch;
while((num=br2.read()) != -1)
{
ch=(char)num;
System.out.print(ch);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try {
if (br != null)
br.close();
if (br2 != null)
br2.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
}
}
BufferedReader.
BufferedReader
class.char
for reading the content of file.myfile.txt
and myfile2.txt
. In order to demonstrate both the ways to read file. I’m
reading first file using readLine()
method while the second file is being read using read()
method.
How to write
to a file in java using FileOutputStream
Earlier we
saw how to create a file in Java. In this tutorial we will
see how to write to a file in java using FileOutputStream
. We would be using write() method of FileOutputStream
to write the content to the specified
file. Here is the signature of write()
method.
public void write(byte[] b) throws IOException
It writes b.length
bytes from the specified byte array to
this file output stream. As you can see this method needs array of bytes in
order to write them into a file. Hence we would need to convert our content
into array of bytes before writing it into the file.
FileOutputStream
. We would be using write() method of FileOutputStream
to write the content to the specified
file. Here is the signature of write()
method.b.length
bytes from the specified byte array to
this file output stream. As you can see this method needs array of bytes in
order to write them into a file. Hence we would need to convert our content
into array of bytes before writing it into the file.
Complete Code: Writing to a File
In the below
example we are writing a String
to a file. To convert the String
into an array of bytes, we are using getBytes() method of String class.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
FileOutputStream fos = null;
File file;
String mycontent = "This is my Data which needs" +
" to be written into the file";
try {
//Specify the file path here
file = new File("C:/myfile.txt");
fos = new FileOutputStream(file);
/* This logic will check whether the file
* exists or not. If the file is not found
* at the specified location it would create
* a new file*/
if (!file.exists()) {
file.createNewFile();
}
/*String content cannot be directly written into
* a file. It needs to be converted into bytes
*/
byte[] bytesArray = mycontent.getBytes();
fos.write(bytesArray);
fos.flush();
System.out.println("File Written Successfully");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (fos != null)
{
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error in closing the Stream");
}
}
}
}
Output:
File Written Successfully
String
to a file. To convert the String
into an array of bytes, we are using getBytes() method of String class.
How to write
to file in Java using BufferedWriter
Earlier we
discussed how to write to a file using FileOutputStream. In this
tutorial we will see how to write to a file using BufferedWriter
. We will be using write()
method of BufferedWriter
to write the text into a file. The
advantage of using BufferedWriter
is that it writes text to a
character-output stream, buffering characters so as to provide for the
efficient writing (better performance) of single characters, arrays, and
strings.
BufferedWriter
. We will be using write()
method of BufferedWriter
to write the text into a file. The
advantage of using BufferedWriter
is that it writes text to a
character-output stream, buffering characters so as to provide for the
efficient writing (better performance) of single characters, arrays, and
strings.
Complete example: Write to file using
BufferedWriter
In this example
we have a String mycontent
and a file myfile.txt
in C drive. We are writing the String
to the File
with the help of FileWriter and
BufferedWriter.
package beginnersbook.com;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
BufferedWriter bw = null;
try {
String mycontent = "This String would be written" +
" to the specified File";
//Specify the file name and path here
File file = new File("C:/myfile.txt");
/* This logic will make sure that the file
* gets created if it is not present at the
* specified location*/
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(mycontent);
System.out.println("File written Successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try{
if(bw!=null)
bw.close();
}catch(Exception ex){
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}
}
Output:
File written Successfully
mycontent
and a file myfile.txt
in C drive. We are writing the String
to the File
with the help of FileWriter and
BufferedWriter.
Append to a
file in java using BufferedWriter, PrintWriter, FileWriter
In this
tutorial we will learn how to append content to a file in Java. There are two
ways to append:
1) Using FileWriter
and BufferedWriter
: In this approach we will be having the
content in one of more Strings and we will be appending those Strings to the
file. The file can be appended using FileWriter
alone however using BufferedWriter
improves the performance as it maintains
a buffer.
2) Using PrintWriter
: This is one of best way to append content to a file. Whatever
you write using PrintWriter
object would be appended to the File.
FileWriter
and BufferedWriter
: In this approach we will be having the
content in one of more Strings and we will be appending those Strings to the
file. The file can be appended using FileWriter
alone however using BufferedWriter
improves the performance as it maintains
a buffer.2) Using
PrintWriter
: This is one of best way to append content to a file. Whatever
you write using PrintWriter
object would be appended to the File.
1) Append content to File using
FileWriter and BufferedWriter
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo
{
public static void main( String[] args )
{
try{
String content = "This is my content which would be appended " +
"at the end of the specified file";
//Specify the file name and path here
File file =new File("C://myfile.txt");
/* This logic is to create the file if the
* file is not already present
*/
if(!file.exists()){
file.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(file,true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully appended at the end of file");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:
Data successfully appended at the end of file
Lets say
myfile.txt content was:
This is the already present content of my file
After running
the above program the content would be:
This is the already present content of my fileThis is my content which
would be appended at the end of the specified file
2) Append content to File using
PrintWriter
PrintWriter
gives you more flexibility. Using this
you can easily format the content which is to be appended to the File
.
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo2
{
public static void main( String[] args )
{
try{
File file =new File("C://myfile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();
System.out.println("Data successfully appended at the end of file");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:
Data successfully appended at the end of file
Lets say
myfile.txt content was:
This is the already present content of my file
After running
the above program the content would be:
This is the already present content of my file
This is first line
This is the second line
This is third line
PrintWriter
gives you more flexibility. Using this
you can easily format the content which is to be appended to the File
.
Delete/Rename File
1) How to deletefile in Java using delete() Method
2) How to renamefile in Java using renameTo() method
2) How to renamefile in Java using renameTo() method
0 comments
Thanks for intrest.. We will touch withbyou soon..