Java File Class
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()
4
public String getPath()
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()
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()
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()
16
public void deleteOnExit()
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()
21
public File[] listFiles(FileFilter 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()
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)
30
public int compareTo(Object o)
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.
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 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 9. Name The Filter Stream Classes On Reading Side Of Byte Stream?
Answer :
There are four 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.
○ PipedInputStream
○ PipedOutputStream
○ PipedReader
○ PipedWriter
● These streams are very useful to pass data between two running threads (say,
processes).
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.
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");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:
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();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:
How to delete a File in java. We will be using the delete() method for file deletion.
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!
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
System.out.println("File Compressed!!");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Output:
File Compressed!!
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.
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: