Java.io.File Class in Java
- The File class is Java’s representation of a file or directory path name.
- Because file and directory names have different formats on different platforms, a simple string is not adequate to name them.
- The File class contains several methods for working with the path name, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.
File
How to create a File Object?
A File object is created by passing in a String that represents the name of a file, or a String or another File object. For example,
File a = new File(“/usr/local/bin/geeks”); //this will create object only not any file
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute abstract file name.
Constructors
- File(File parent, String child) : Creates a new File instance from a parent abstract pathname and a child pathname string.
- File(String pathname) : Creates a new File instance by converting the given pathname string into an abstract pathname.
- File(String parent, String child) : Creates a new File instance from a parent pathname string and a child pathname string.
- File(URI uri) : Creates a new File instance by converting the given file: URI into an abstract pathname.
Methods
- boolean canExecute() : Tests whether the application can execute the file denoted by this abstract pathname.
- boolean canRead() : Tests whether the application can read the file denoted by this abstract pathname.
- boolean canWrite() : Tests whether the application can modify the file denoted by this abstract pathname.
- int compareTo(File pathname) : Compares two abstract pathnames lexicographically.
- boolean createNewFile() : Atomically creates a new, empty file named by this abstract pathname .
- static File createTempFile(String prefix, String suffix) : Creates an empty file in the default temporary-file directory.
- boolean delete() : Deletes the file or directory denoted by this abstract pathname.
- boolean equals(Object obj) : Tests this abstract pathname for equality with the given object.
- boolean exists() : Tests whether the file or directory denoted by this abstract pathname exists.
- String getAbsolutePath() : Returns the absolute pathname string of this abstract pathname.
- long getFreeSpace() : Returns the number of unallocated bytes in the partition .
- String getName() : Returns the name of the file or directory denoted by this abstract pathname.
- String getParent() : Returns the pathname string of this abstract pathname’s parent.
- File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent.
- String getPath() : Converts this abstract pathname into a pathname string.
- boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
- boolean isFile() : Tests whether the file denoted by this abstract pathname is a normal file.
- boolean isHidden() : Tests whether the file named by this abstract pathname is a hidden file.
- long length() : Returns the length of the file denoted by this abstract pathname.
- String[] list() : Returns an array of strings naming the files and directories in the directory .
- File[] listFiles() : Returns an array of abstract pathnames denoting the files in the directory.
- boolean mkdir() : Creates the directory named by this abstract pathname.
- boolean renameTo(File dest) : Renames the file denoted by this abstract pathname.
- boolean setExecutable(boolean executable) : A convenience method to set the owner’s execute permission.
- boolean setReadable(boolean readable) : A convenience method to set the owner’s read permission.
- boolean setReadable(boolean readable, boolean ownerOnly) : Sets the owner’s or everybody’s read permission.
- boolean setReadOnly() : Marks the file or directory named so that only read operations are allowed.
- boolean setWritable(boolean writable) : A convenience method to set the owner’s write permission.
- String toString() : Returns the pathname string of this abstract pathname.
- URI toURI() : Constructs a file URI that represents this abstract pathname.
FileWriter
FileWriter is useful to create a file writing characters into it.
- This class inherits from the OutputStream class.
- The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
- FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
- FileWriter creates the output file , if it is not present already.
Constructors:
- FileWriter(File file) – Constructs a FileWriter object given a File object.
- FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
- FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.
- FileWriter (String fileName) – constructs a FileWriter object given a file name.
- FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.
Methods:
Reading and writing take place character by character, which increases the number of I/O operations and effects performance of the system.BufferedWriter can be used along with FileWriter to improve speed of execution.
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
- This class inherit from the InputStreamReader Class.
- The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
- FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
Constructors:
- FileReader(File file) – Creates a FileReader , given the File to read from
- FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from
- FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from
Methods:
- public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.
- public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
- public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read - public void close() throws IOException closes the reader.
- public long skip(long n) throws IOException –Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached.
Parameters:
n – The number of characters to skip
Following program depicts how to read from the ‘text’ file using FileReader
// Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;
// check if File exists or not
FileReader fr=null;
try
{
fr = new FileReader(“text”);
}
catch (FileNotFoundException fe)
{
System.out.println(“File not found”);
}
// read from FileReader till the end of file
while ((ch=fr.read())!=-1)
System.out.print((char)ch);
// close the file
fr.close();
}
}
BufferedWriter
- BufferredWriter class writes text to character-output stream, buffering characters.
- Thus, providing efficient writing of single array, character and strings.
- A buffer size needs to be specified, if not it takes Default value.
- An output is immediately set to the underlying character or byte stream by the Writer.
Class Declaration
public class BufferedWriter
extends Writer
Constructors
- BufferedWriter(Writer out): Creates a buffered character-output stream that uses a default-sized output buffer.
- BufferedWriter(Writer out, int size): Creates a new buffered character-output stream that uses an output buffer of the given size.
Methods:
write() : java.io.BufferedWriter.write(int arg) writes a single character that is specified by an integer argument.
Syntax :
public void write(int arg)
Parameters :
arg : integer that specifies the character to write
Return :
Doesn’t return any value.
write() : java.io.BufferedWriter.write(String arg, int offset, int length) writes String in the file according to its arguments as mentioned in the Java Code.
Syntax :
public void write(String arg, int offset, int length)
Parameters :
arg : String to be written
offset : From where to start reading the string
length : No. of characters of the string to write
Return :
Doesn’t return any value.
newLine() : java.io.BufferedWriter.newLine() breaks/separates line.
Syntax :
public void newLine()
Return :
Doesn’t return any value.
flush() : java.io.BufferedWriter.flush() flushes character from write buffer.
Syntax :
public void flush()
Return :
Doesn’t return any value.
close() : java.io.BufferedWriter.close() flushes character from write buffer and then close it.
Syntax :
public void close()
Return :
- Doesn’t return any value.
BufferedReader
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
- The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
- In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.
- It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.
- Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
Constructors:
- BufferedReader(Reader in) : Creates a buffering character-input stream that uses a default-sized input buffer.
- BufferedReader(Reader in, int sz) : Creates a buffering character-input stream that uses an input buffer of the specified size
PrintWriter
This class gives Prints formatted representations of objects to a text-output stream. It implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
Constructor and Description
- PrintWriter(File file) : Creates a new PrintWriter, without automatic line flushing, with the specified file.
- PrintWriter(File file, String csn) : Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
- PrintWriter(OutputStream out) : Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
- PrintWriter(OutputStream out, boolean autoFlush) : Creates a new PrintWriter from an existing OutputStream.
- PrintWriter(String fileName) : Creates a new PrintWriter, without automatic line flushing, with the specified file name.
- PrintWriter(String fileName, String csn) : Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.
- PrintWriter(Writer out): Creates a new PrintWriter, without automatic line flushing.
- PrintWriter(Writer out, boolean autoFlush) : Creates a new PrintWriter.
Methods:
- PrintWriter append(char c) : Appends the specified character to this writer
- PrintWriter append(CharSequence csq, int start, int end): Appends the specified character sequence to this writer.
- PrintWriter append(CharSequence csq) : Appends a subsequence of the specified character sequence to this writer.
- boolean checkError(): Flushes the stream and checks its error state.