You are on page 1of 19

Java File Class

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

1
public String getName()

Returns the name of the file or directory denoted by this abstract pathname.

2
public String getParent()

Returns the pathname string of this abstract pathname's parent, or null if this
pathname does not name a parent directory.

3
public File getParentFile()

Returns the abstract pathname of this abstract pathname's parent, or null if


this pathname does not name a parent directory.

4
public String getPath()

Converts this abstract pathname into a pathname string.

5
public boolean isAbsolute()
Tests whether this abstract pathname is absolute. Returns true if this abstract
pathname is absolute, false otherwise.

6
public String getAbsolutePath()

Returns the absolute pathname string of this abstract pathname.

7
public boolean canRead()

Tests whether the application can read the file denoted by this abstract
pathname. Returns true if and only if the file specified by this abstract
pathname exists and can be read by the application; false otherwise.

8
public boolean canWrite()

Tests whether the application can modify to the file denoted by this abstract
pathname. Returns true if and only if the file system actually contains a file
denoted by this abstract pathname and the application is allowed to write to
the file; false otherwise.

9
public boolean exists()

Tests whether the file or directory denoted by this abstract pathname exists.
Returns true if and only if the file or directory denoted by this abstract
pathname exists; false otherwise.
10
public boolean isDirectory()

Tests whether the file denoted by this abstract pathname is a directory.


Returns true if and only if the file denoted by this abstract pathname exists
and is a directory; false otherwise.

11
public boolean isFile()

Tests whether the file denoted by this abstract pathname is a normal file. A file
is normal if it is not a directory and, in addition, satisfies other
system-dependent criteria. Any non-directory file created by a Java
application is guaranteed to be a normal file. Returns true if and only if the file
denoted by this abstract pathname exists and is a normal file; false otherwise.

12
public long lastModified()

Returns the time that the file denoted by this abstract pathname was last
modified. Returns a long value representing the time the file was last
modified, measured in milliseconds since the epoch (00:00:00 GMT, January
1, 1970), or 0L if the file does not exist or if an I/O error occurs.

13
public long length()

Returns the length of the file denoted by this abstract pathname. The return
value is unspecified if this pathname denotes a directory.
14
public boolean createNewFile() throws IOException

Atomically creates a new, empty file named by this abstract pathname if and
only if a file with this name does not yet exist. Returns true if the named file
does not exist and was successfully created; false if the named file already
exists.

15
public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this


pathname denotes a directory, then the directory must be empty in order to be
deleted. Returns true if and only if the file or directory is successfully deleted;
false otherwise.

16
public void deleteOnExit()

Requests that the file or directory denoted by this abstract pathname be


deleted when the virtual machine terminates.

17
public String[] list()

Returns an array of strings naming the files and directories in the directory
denoted by this abstract pathname.

18
public String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.

20
public File[] listFiles()

Returns an array of abstract pathnames denoting the files in the directory


denoted by this abstract pathname.

21
public File[] listFiles(FileFilter filter)

Returns an array of abstract pathnames denoting the files and directories in


the directory denoted by this abstract pathname that satisfy the specified filter.

22
public boolean mkdir()

Creates the directory named by this abstract pathname. Returns true if and
only if the directory was created; false otherwise.

23
public boolean mkdirs()

Creates the directory named by this abstract pathname, including any


necessary but nonexistent parent directories. Returns true if and only if the
directory was created, along with all necessary parent directories; false
otherwise.
24
public boolean renameTo(File dest)

Renames the file denoted by this abstract pathname. Returns true if and only
if the renaming succeeded; false otherwise.

25
public boolean setLastModified(long time)

Sets the last-modified time of the file or directory named by this abstract
pathname. Returns true if and only if the operation succeeded; false
otherwise.

26
public boolean setReadOnly()

Marks the file or directory named by this abstract pathname so that only read
operations are allowed. Returns true if and only if the operation succeeded;
false otherwise.

27
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException

Creates a new empty file in the specified directory, using the given prefix and
suffix strings to generate its name. Returns an abstract pathname denoting a
newly-created empty file.
28
public static File createTempFile(String prefix, String suffix) throws
IOException

Creates an empty file in the default temporary-file directory, using the given
prefix and suffix to generate its name. Invoking this method is equivalent to
invoking createTempFile(prefix, suffix, null). Returns abstract pathname
denoting a newly-created empty file.

29
public int compareTo(File pathname)

Compares two abstract pathnames lexicographically. Returns zero if the


argument is equal to this abstract pathname, a value less than zero if this
abstract pathname is lexicographically less than the argument, or a value
greater than zero if this abstract pathname is lexicographically greater than
the argument.

30
public int compareTo(Object o)

Compares this abstract pathname to another object. Returns zero if the


argument is equal to this abstract pathname, a value less than zero if this
abstract pathname is lexicographically less than the argument, or a value
greater than zero if this abstract pathname is lexicographically greater than
the argument.

31
public boolean equals(Object obj)
Tests this abstract pathname for equality with the given object. Returns true if
and only if the argument is not null and is an abstract pathname that denotes
the same file or directory as this abstract pathname.

32
public String toString()

Returns the pathname string of this abstract pathname. This is just the string
returned by the getPath() method.

JAVA INTERVIEW QUESTIONS

Question 1. What Is A Io Stream?


Answer :
It is a stream of data that flows from source to destination. Good example is file copying. Two
streams are involved – input stream and output stream. An input stream reads from the file
and stores the data in the process (generally in a temporary variable). The output stream reads
from the process and writes to the destination file.

Question 2. What Is The Necessity Of Two Types Of Streams – Byte Streams And Character
Streams?
Answer :
Byte streams were introduced with JDK 1.0 and operate on the files containing ASCII
characters. We know Java supports other language characters also known as Unicode
characters. To read the files containing Unicode characters, the designers introduced
character streams with JDK 1.1. As ASCII is a subset of Unicode, for the files of English
characters, we can go with either byte streams or character streams.

Question 3. What Are The Super Most Classes Of All Streams?


Answer :
All the byte stream classes can be divided into two categories (input stream classes and
output stream classes) and all character streams classes into two (reader classes and writer
classes). There are four abstract classes from which all these streams are derived. The super
most class of all byte stream classes is java.io.InputStream and for all output stream classes,
java.io.OutputStream. Similarly for all reader classes is java.io.Reader and for all writer classes
is java.io.Writer.

Question 4. What Are Fileinputstream And Fileoutputstream?


Answer :
These two are general purpose classes used by the programmer very often to copy file to file.
These classes work well with files containing less data of a few thousand bytes as by
performance these are very poor. For larger data, it is preferred to use BufferedInputStream (or
Buffered Reader) and BufferedOutputStream (or BufferedWriter).

Question 5. Which You Feel Better To Use – Byte Streams Or Character Streams?
Answer :
I feel personally to go with character streams as they are the latest. Many features exist in
character streams that do not in byte streams like a) using BufferedReader in place of
BufferedInputStream and DataInputStream (one stream for two) and b) using newLine()
method to go for next line and for this effect we must go for extra coding in byte streams etc.

Question 6. What System.out.println()?


Answer :
"println()" is a method of PrintStream class. "out" is a static object of PrintStream class defined
in "System" class. System is a class from java.lang package used to interact with the
underlying operating system by the programmer.

Question 7. What Are Filter Streams?


Answer :
Filter streams are a category of IO streams whose responsibility is to add extra functionality
(advantage) to the existing streams like giving line numbers in the destination file that do not
exist int the source file or increasing performance of copying etc.

Question 8. Name The Filter Streams Available?


Answer :
There are four filter streams in java.io package – two in byte streams side and two in character
streams side. They are FilterInputStream, FilterOutputStream, FilterReader and FilterWriter.
These classes are abstract classes and you cannot create of objects of these classes.

Question 9. Name The Filter Stream Classes On Reading Side Of Byte Stream?
Answer :
There are four classes:–

○ LineNumberInputStream (the extra functionality is it adds line numbers in


the destination file),
○ DataInputStream (contains special methods like readInt(), readDouble()
and readLine() etc that can read an int, a double and a string at a time),
○ BufferedInputStream (gives buffering effect that increases the
performance to the peak)
○ PushbackInputStream (pushes the required character back to the
system).

Question 10. What Is The Functionality Of Sequence Input Stream?


Answer :
It is very useful to copy multiple source files into one destination file with very less code.

Question 11. What Is Print Stream And Print Writer?


Answer :
Functionally both are same but belong to two different categories – byte streams and
character streams. println() method exists in both classes.

Question 12. Which Streams Are Advised To Use To Have Maximum Performance In File
Copying?
Answer :
BufferedInputStream and BufferedOutputStream on byte streams side and BufferedReader
and BufferedWriter on character streams side.

Question 13. What Are Piped Streams?


Answer :
There are four piped streams:–

○ PipedInputStream
○ PipedOutputStream
○ PipedReader
○ PipedWriter
● These streams are very useful to pass data between two running threads (say,
processes).

Question 14. What Is File Class?


Answer :
It is a non-stream (not used for file operations) class used to know the properties of a file like
when it was created (or modified), has read and write permissions, size etc.

Question 15. What Is Randomaccessfile?


Answer :
It is a special class from java.io package which is neither a input stream nor a output stream
(because it can do both). It is directly a subclass of Object class. Generally, a stream does only
one purpose of either reading or writing; but RandomAccessFile can do both reading from a
file and writing to a file. All the methods of DataInputStream and DataOutStream exist in
RandomAccessFile.
Append to a file in java using BufferedWriter, PrintWriter, FileWriter

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.

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
How to delete file in Java – delete() Method

How to delete a File in java. We will be using the delete() method for file deletion.

public boolean delete()


This method returns true if the specified File deleted successfully otherwise it returns false.

Here is the complete code:

import java.io.File;
public class DeleteFileJavaDemo
{
public static void main(String[] args)
{
try{
//Specify the file name and path
File file = new File("C:\\myfile.txt");
/*the delete() method returns true if the file is
* deleted successfully else it returns false
*/
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete failed: File didn't delete");
}
}catch(Exception e){
System.out.println("Exception occurred");
e.printStackTrace();
}
}
}
Output:

myfile.txt is deleted!

How to Compress a File in GZIP Format

BY CHAITANYA SINGH | FILED UNDER: JAVA I/O


The below code would compress a specified file to GZip format. In the below example we have a
text file in B drive under “Java” Folder and we are compressing and generating the GZip file in
the same folder.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GZipExample


{
public static void main( String[] args )
{
GZipExample zipObj = new GZipExample();
zipObj.gzipMyFile();
}

public void gzipMyFile(){


byte[] buffer = new byte[1024];
try{
//Specify Name and Path of Output GZip file here
GZIPOutputStream gos =
new GZIPOutputStream(new
FileOutputStream("B://Java/Myfile.gz"));

//Specify location of Input file here


FileInputStream fis =
new FileInputStream("B://Java/Myfile.txt");

//Reading from input file and writing to output GZip file


int length;
while ((length = fis.read(buffer)) > 0) {

/* public void write(byte[] buf, int off, int len):


* Writes array of bytes to the compressed output stream.
* This method will block until all the bytes are written.
* Parameters:
* buf - the data to be written
* off - the start offset of the data
* len - the length of the data
*/
gos.write(buffer, 0, length);
}
fis.close();

/* public void finish(): Finishes writing compressed


* data to the output stream without closing the
* underlying stream.
*/
gos.finish();
gos.close();

System.out.println("File Compressed!!");

}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Output:

File Compressed!!

How to get the last modified date of a file in java

Here we will learn how to get the last modified date of a file in java. In order to do this we can
use the lastModified() method of File class. Following is the signature of this method.

public long lastModified()


It returns the time that the file denoted by this abstract pathname was last modified. The value
returned by this method is in milliseconds so in order to make it readable, we can format the
output using SimpleDateFormat.

Complete code:
Here we are fetching the last modified date of file “Myfile.txt” which is present in drive “C”. Since
the value returned by method is not readable, we are using format() method of
SimpleDateFormat class to format it.

import java.io.File;
import java.text.SimpleDateFormat;
public class LastModifiedDateExample
{
public static void main(String[] args)
{
//Specify the file path and name
File file = new File("C:\\Myfile.txt");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy
HH:mm:ss");
System.out.println("Last Modified Date: " +
sdf.format(file.lastModified()));
}
}
Output:

Last Modified Date: 01/03/2014 22:41:49


We can format and display the output in any desired format. For example if we use the following
pattern:

SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yy HH:mm a");


System.out.println("Last Modified Date: " +
sdf2.format(file.lastModified()));
We will get the below output for above pattern:

Last Modified Date: 01-03-14 22:41 PM

You might also like