File1
File1
https://sites.google.com/a/tges.org/computer-education/home/isc-10th/file-handling
File Handling
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All
these streams represent an input source and an output destination. The stream in the java.io package supports many
data such as primitives, Object, localized characters etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination.
Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers very basic
functionlity related to streams and I/O. We would see most commonly used example one by one:
Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to
the console, you wrap System.in in aBufferedReader object, to create a character stream. Here is most common
syntax to obtain BufferedReader:
Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a
string from the console.
To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It
returns .1 when the end of the stream is encountered. As you can see, it can throw an IOException.
The following program demonstrates read( ) by reading characters from the console until the user types a "q":
import java.io.*;
class BRRead
{
public static void main(String args[]) throws IOException
{
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do
{
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run:
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its
general form is shown here:
The following program demonstrates BufferedReader and the readLine( ) method. The program reads and displays
lines of text until you enter the word "end":
Console output is most easily accomplished with print( ) and println( ), described earlier. These methods are
defined by the class PrintStream which is the type of the object referenced by System.out. Even though System.out
is a byte stream, using it for simple program output is still acceptable.
Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method
write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is
shown here:
This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the
low-order eight bits are written.
Example:
Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:
import java.io.*;
// Demonstrate System.out.write().
class WriteDemo
{
public static void main(String args[])
{
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Note: You will not often use write( ) to perform console output because print( ) and println( ) are substantially easier
to use.
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and there are
several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file.:
Following constructor takes a file object to create an input stream object to read the file. First we create a file object
using File() method as follows:
Once you have InputStream object in hand then there is a list of helper methods which can be used to read to stream
or to do other operations on the stream.
There are other important input streams available, for more detail you can refer to the following links:
ByteArrayInputStream
DataInputStream
FileOutputStream:
FileOutputStream is used to create a file and write data into it.The stream would create a file, if it doesn't already
exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file.:
Following constructor takes a file object to create an output stream object to write the file. First we create a file
object using File() method as follows:
Once you have OutputStream object in hand then there is a list of helper methods which can be used to write to
stream or to do other operations on the stream.
There are other important output streams available, for more detail you can refer to the following links:
ByteArrayOutputStream
DataOutputStream
Example:
The above code would create file test.txt and would write given numbers in binary format. Same would be output on
the stdout screen.
There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.
File Class
FileReader Class
FileWriter Class
Directories in Java:
Creating Directories:
There are two useful File utility methods which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that
the path specified in the File object already exists, or that the directory cannot be created because the entire
path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
import java.io.File;
class CreateDir
{
public static void main(String args[])
{
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a
forward slash (/) on a Windows version of Java, the path will still resolve correctly.
Reading Directories:
A directory is a File that contains a list of other files and directories. When you create a File object and it is a
directory, the isDirectory( ) method will return true.
You can call list( ) on that object to extract the list of other files and directories inside. The program shown here
illustrates how to use list( ) to examine the contents of a directory:
import java.io.File;
class DirList
{
public static void main(String args[])
{
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}
https://www.includehelp.com/java-programs/file-handling-programs.aspx
List of Java File Handling Programs
Program
Qno
1 Java program to create a new file
9 Java program to get the last modification date and time of a file
12 Java program to read text from file from a specified index or skipping byte using FileInputStream
14 Java program to get the size of given file in bytes, kilobytes and megabytes
17 Java program to read and print all files from a zip file
21 Java program to get file creation, last access and last modification time
22 Java program to read content from one file and write it into another file
26 Java - Copy Content of One File to Another File using Java Program
File class is used for file related operations, in this program we will use createNewFile() method of File class
that will return boolean value, if file is created successfully, method will retutn true otherwise it will return
false.
import java.io.File;
try
{
File objFile = new File(fileName);
if (objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
}
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}
Output:
Q2
Java program to write content into file using
FileOutputStream
This program will write the content into the file using FileOutputStream class. In this
program we are using FileOutputStream.write() method which writes the value in
bytes, so we have to convert String data into bytes.
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
//object of FileOutputStream
FileOutputStream fileOut = new FileOutputStream(objFile);
//convert text into Byte and write into file
fileOut.write(text.getBytes());
fileOut.flush();
fileOut.close();
System.out.println("File saved.");
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}
Output:
import java.io.File;
import java.io.FileInputStream;
//object of FileOutputStream
FileInputStream fileIn = new FileInputStream(objFile);
//read text from file
System.out.println("Content of the file is: ");
while ((val = fileIn.read()) != -1)
{
System.out.print((char) val);
}
System.out.println();
fileIn.close();
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}
Output
Content of the file is:
Java is a platform independent language.
Q4
Java program to write content into file using
BufferedWriter
This program will write the content (string data) into the file
using BufferedWriter class. We will create a file named "file2.txt" in the same
directory.
BufferWriter takes the FileWriter type argument and FileWriter class defines that
file. So we have to create mainly three object:
BufferedWriter.write() - This method is used to write String data into the file.
Program will read content from the file line by line until null is not found.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Scanner;
//instance of FileWriter
FileWriter objFileWriter = new FileWriter(objFile.getAbsoluteFile());
//instnace (object) of BufferedReader with respect of FileWriter
BufferedWriter objBW = new BufferedWriter(objFileWriter);
//write into file
objBW.write(text);
objBW.close();
System.out.println("File saved.");
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}
Output:
Q5
Java program to write content into file using
BufferedWriter
This program will write the content (string data) into the file
using BufferedWriter class. We will create a file named "file2.txt" in the same
directory.
BufferWriter takes the FileWriter type argument and FileWriter class defines that
file. So we have to create mainly three object:
BufferedWriter.write() - This method is used to write String data into the file.
Program will read content from the file line by line until null is not found.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Scanner;
//instance of FileWriter
FileWriter objFileWriter = new FileWriter(objFile.getAbsoluteFile());
//instnace (object) of BufferedReader with respect of FileWriter
BufferedWriter objBW = new BufferedWriter(objFileWriter);
//write into file
objBW.write(text);
objBW.close();
System.out.println("File saved.");
} catch (Exception Ex) {
System.out.println("Exception : " + Ex.toString());
}
}
}
Output:
Q6
Java program to get file size and file path
This program will print the exact (absolute) path of the file and file length i.e. file size in
bytes, to get the file path we will use the File.getAbsolutePath() method and to get
file length (size) we will use File.length() Method.
File.getAbsolutePath() - Method return absolute path of the file, this is the method
of File class.
File.length() - Method returns the file size (length) in the bytes, this is also method of
File class.
import java.io.File;
}
}
Output:
Q7
Java program to delete a file
This program will delete an existing file. There is a method delete() of File class
which is used to delete the file and returns true or false, if the file deletes method
returns true otherwise false.
import java.io.File;
public class ExDeleteFile {
public static void main(String args[]) {
final String fileName = "file3.txt";
Output:
Q8
Java program to copy files
This program will copy files in Java.
import java.io.*;
Output:
Q9
Java program to get the last modification date
and time of a file
In this java program, we will learn how to get the file's last modification date and
time? Here, we will give a file name and program will print its last modification date
and time.
Submitted by IncludeHelp, on October 17, 2017
Given a file name and we have to find its last modification date using java
program.
import java.io.*;
import java.util.Date;
{
// Enter the file name here.
File file = new File("E:/IncludeHelp.txt");
Output
Q10
Java program to append text/string in a file
In this java program, we are going to learn how to append text/string in a given
file? Here, we have a file with some pre written content and we are appending text in
it.
Submitted by IncludeHelp, on October 19, 2017
Given a file and we have to append text/string in the file using java program.
Example:
import java.io.*;
try {
//file output stream to open and write data
FileOutputStream fos = new FileOutputStream(strFilePath, true);
//string to be appended
String strContent = "Text to be appended.";
//appending text/string
fos.write(strContent.getBytes());
Output
Q11
Java program to determine number of bytes
written to file using DataOutputStream
In this java program, we are going to learn how to get (determine) the number of
bytes written to a file using DataOutputStream? Here, we will write text in file
and print the number of written bytes.
Submitted by IncludeHelp, on October 19, 2017
Given a file and we have to write text and print the total number of written
bytes using DataOutputSteam using Java program.
Example:
First of all we will create an object of FileOutputStream by passing the file’s path and
then we will create an object of DataOutputStream by passing object
of FileOutputStream.
Then, we will write the text into file using writeBytes() method
of DataOutputStream and finally we will get the size of the file by using size() method
of DataOutputStream class.
In this program,
import java.io.*;
objDOS.close();
} catch (Exception ex) {
System.out.println("Exception: " + ex.toString());
}
}
}
Output
Q12
Java program to read text from file from a
specified index or skipping byte using
FileInputStream
In this program, we are going to learn how to read text from a file after skipping
some bytes and print them on the output screen using FileInputStream.
Submitted by IncludeHelp, on October 19, 2017
Given a file with some text and we have to print text after skipping some
bytes using FileInputStream in Java.
Example:
File's content is: "The quick brown fox jumps over the lazy dog."
After skipping starting 10 bytes...
Output: "brown fox jumps over the lazy dog."
import java.io.*;
try {
FileInputStream fin = new FileInputStream(file);
int ch;
System.out.println("File's content after 10 bytes is: ");
Output
Q13
Java program to check whether a file is hidden
or not
In this java program, we are going to learn, how to check whether a file is hidden
or not? Method isHidden() of "File" class is used to check it.
Submitted by IncludeHelp, on October 27, 2017
Given a file, and we have to check whether it is hidden or not using Java
program?
File.isHidden()
This is a method of "File" class, which returns true if a file has hidden property and
return false if it is not.
Output
Here, we are using an another method file.getPath() which returns the file name
with path of that file, which is used while creating an object of “File” class.
Q14
Java program to get the size of give file in bytes,
kilobytes and megabytes
In this Java program, we are going to learn how to get the size of a given file in
bytes, kilobytes and megabytes?
Submitted by IncludeHelp, on October 27, 2017
Given a file and we have to get the file size using Java program.
File.length()
This is a method of "File" class, which returns the file’s length (file size) in bytes.
Q15
Java program to create directory/folder in
particular drive
In this Java program, we will learn how we can create a directory or a folder? To
create a directory, we use File.mkdir() method in Java.
Submitted by IncludeHelp, on October 27, 2017
File.mkdir()
This is a method of "File" class in Java and used to create a directory at specified path,
it return true if directory creates or returns false if directory does not create.
Here, first of all we are creating an object name dir of "File" class by specifying
the "directory name with the path (drive name)" and then we are
using dir.mkdir() method to create directory (Here, dir is an object of "File" class).
//displaying results
if (isDirectoryCreated)
System.out.println("Directory successfully created: " + dir);
else
System.out.println("Directory was not created successfully: " + dir);
}
}
Output
Q16
Java program to check whether a file can be
read or not
In this java program, we are going to check whether a given file can be read or
not? To check this, we are using File.canRead() method.
Submitted by IncludeHelp, on October 28, 2017
Given a file, and we have to check whether file can be read or not using Java
program.
In this program, there is a file named "C.txt" which is saved in "E:\" drive in my
system, so that path is "E:/C.txt".
To check that file can be read or not, there is a method canRead() of "File" class, it
returns 'true' if file can be read or returns 'false' if file cannot be read.
if (file.canRead()) {
System.out.println("File " + file.getPath() + " can be read");
} else {
System.out.println("File " + file.getPath() + " can not be read");
}
}
}
Output
Q17
Java program to read and print all files from a zip
file
In this java program, we are going to learn how to read a zip file and access all
files from it? Here, we will have a zip file, read files from it and print file names.
Submitted by IncludeHelp, on November 03, 2017
Given a zip file, and we have to print all files names from it using java
program.
To implement this java program, we are going to use main classes FileInputStream to
manage normal files by creating its object, and ZipInputStream to manage zip files by
creating its object.
1. getNextEntry() - this will check whether next file (while calling it in the loop) is
available in the zip file or not.
2. getName() - to get file’s name from the zip file.
Program to extract the names of files from zip file in java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
try {
fis = new FileInputStream(filePath);
Zis = new ZipInputStream(new BufferedInputStream(fis));
Output
Q18
Java program to get the attributes of a file
In this java program, we are going to learn how to get and print the attributes of a
file? Here, we are accessing the attributes like file creation time, last access time, last
modified time, file key etc.
Submitted by IncludeHelp, on November 07, 2017
Given a file and we have to find its attributes using java program.
Following packages are using here, to implement this program,
java.nio.file.*
java.nio.file.attribute.*
There are following two important classes, which are using this program to get the file
attributes,
BasicFileAttributeView
BasicFileAttributes
Output
Q19
Java program to get the basic file attributes
(specific to DOS)
In this java program, we are going to learn how to get DOS based basic attributes
like file’s hidden, read-only property etc?
Submitted by IncludeHelp, on November 07, 2017
Given a file and we have to find its attributes using java program.
java.nio.file.*
java.nio.file.attribute.*
There are following two important classes, which are using this program to get the DOS
based file attributes
DosFileAttributeView
DosFileAttributes
First run:
Enter the file path : E:/JAVA
isArchive: false
isHidden: true
isReadOnly: false
isSystem: false
Second run:
Enter the file path : D:/Study
isArchive: false
isHidden: false
isReadOnly: false
isSystem: false
Q20
Java program to get the file's owner name
In this java program, we are going to learn how to get the file's owner name?
Method getOwner() of class FileOwnerAttributeView is used to get the owner
name.
Submitted by IncludeHelp, on November 07, 2017
Given a file and we have to get, print the file's owner name.
java.nio.file.*
java.nio.file.attribute.*
There are following two important classes, which are using this program to get the file's
owner name.
FileOwnerAttributeView
UserPrincipal
The method getOwner() gives the owner's name to the object of UserPrincipal class,
which can be accessed through getName() method.
// print information.
System.out.println("Owner of the file is :" + userPrincipal.getName());
}
}
Output
Q21
Java program to get file creation, last access and
last modification time
In this java program, we are going to learn how to access file’s last access time,
creation time and last modified time using BasicFileAttributes class.
Submitted by IncludeHelp, on November 12, 2017
Given a file and we have to access its creation, last access and last modified
time using Java program.
java.nio.file.*
java.nio.file.attribute.*
java.util.Calendar;
Output
Q22
Java program to read content from one file and
write it into another file
In this java program, we are going to learn how to read content from one file and
write it into another file?
Submitted by IncludeHelp, on November 19, 2017
Given a file and we have to read content from it and write in another file
using java program. This is an example of File Handling in Java.
Output
File Copied...
Q23
Java program to read a file line by line
In this java program, we are going to learn how to read a file line by line and print
the line on the output screen? Here, we are reading content of a file line by line and
printing.
Submitted by IncludeHelp, on November 19, 2017
Given a file and we have to read its content line by line using java program.
For this program, I am using a file named "B.txt" which is located at "E:\" drive, hence
the path of the file is "E:\B.txt", and the content of the file is:
This is line 1
This is line 2
This is line 3
This is line 4
Output
Q24
Java program to traverse all files of a
directory/folder
In this java program, we are going to learn how to access and traverse all files of a
directory/folder? Here, we are traversing all files of a given directory.
Submitted by IncludeHelp, on December 05, 2017
Given a directory (folder) and we have to traverse its all files using java
program.
Example:
Input:
Enter path: 'E:\Java'
(Java folder in 'E' drive)
Output:
About to traverse the directory: JAVA
About to traverse the directory: 1 Nov
Visiting file:ChristmasTree.java
Visiting file:Find Files in Zip File.docx
Finished with the directory: 1 Nov
About to traverse the directory: 2 Nov
Visiting file:Combine Path.docx
Visiting file:CombinePath.java
Finished with the directory: 2 Nov
About to traverse the directory: 3 Nov
Visiting file:Check absolute path.docx
Visiting file:CheckAbsolutePath.java
Finished with the directory: 2 Nov
public ListFiles() {
indentionLevel = 0;
}
Output
Q25
Java - Print File Content, Display File
In this code snippet, we will print the file size and file content using Java program.
import java.io.*;
//close file
inFile.close();
}
}
Output:
Q26
Java - Copy Content of One File to Another File
In this code snippet, we will learn how to copy content of one file to another file using
Java program. In this example we will copy file named "sample.txt" to
"sampleCopy.txt".
import java.io.*;
System.out.println("File copied.");
//close files
inFile.close();
outFile.close();
}
}
Output:
Q27
Java program to rename an existing file
In this Java program, we are going to learn how to rename an existing file? This
task can we performed using 'renameTo()' method, which is a method of 'File'
class.
To rename a file name, we use renameTo() method, which is a method of File class.
Here, we are using statement File F=new File("f:/Includehelp.txt"); to create
an object of File class by passing file name. Here, "Includehelp.txt" is the file name,
which is saved in "f:" drive.
import java.io.File;
import java.io.IOException;
Output