Java Files
Java provides a number of different classes and methods for utilizing files and a computer’s file system. They include the File, FileReader, and FileWriter classes (all from the java.io package).
Accessing Files
Files and directories can be accessed with the File class.
Syntax
import java.io.File;
File myFile = new File(pathString);
The constructor of the File class accepts a pathString that specifies path/filename. Once declared, the new myFile object can be used to manipulate and gather information about the file or directory specified by pathString.
Methods
The File object includes the following methods to manipulate the specified file or directory:
canRead(): Returnstrueif the file is readable.canWrite(): Returnstrueif the file is writable.createNewFile(): Creates an empty file. Returnstrueif successful.delete(): Deletes a file. Can delete a directory if it is empty.exists(): Returnstrueif the file/directory exists.getName(): Returns the name of the file/directory.getAbsolutePath(): Returns the full pathname of the file/directory.isDirectory(): Returnstrueif instance points to a directory.isFile(): Returnstrueif instance points to a file.length(): Returns the size of the file in bytes.list(): Returns aString[]array of the files in the directory.mkdir(): Creates a directory.
Example
The following example creates a File object, checks if its corresponding file exists, and if not, creates it (file access is placed within a try ... catch block in case the file system throws any errors):
import java.io.File;import java.io.IOException;public class FileExample {public static void main(String[] args) {try {File myFile = new File("test.txt");if (myFile.exists()) {System.out.println("File exists: " + myFile.getName());} else {if (myFile.createNewFile()) {System.out.println("File created: " + myFile.getName());} else {System.out.println("File was not created.");}}} catch (IOException e) {System.out.println("An error was thrown.");e.printStackTrace();}}}
Writing to a File
Data can be written to a file with the FileWriter class.
Syntax
import java.io.FileWriter;
FileWriter myWriter = new FileWriter(pathString, append);
The constructor of the FileWriter class takes a pathString that specifies a path/filename. Once declared, the new myWriter object can be used to write to the file specified by pathString. The optional append boolean specifies if writing will append to the file.
Methods
The following methods are provided by the FileWriter:
close(): Closes theFileWriter. Should be done after all writes are complete.write(): Writes a string or char sequence to the file.
Example
The following example writes a string out to a file (again, within a try ... catch block):
import java.io.FileWriter;import java.io.IOException;public class FileWriterExample {public static void main(String[] args) {try {FileWriter myWriter = new FileWriter("test.txt");myWriter.write("Hello World!");myWriter.close();} catch (IOException e) {System.out.println("An error was thrown.");e.printStackTrace();}}}
Reading Files
Data can be read from a file with the FileReader class.
Syntax
import java.io.FileReader;
FileReader myReader = new FileReader(pathString);
The constructor of the FileReader class takes a pathString that specifies a path/filename. Once declared, the new myReader object can be used to read characters from the file specified by pathString.
Methods
The FileReader class offers the following methods to read from a file:
close(): Closes theFileReader. Should be done after all reads are complete.read(): Reads a character from the file, or reads characters into a buffer.
Example
The following example reads all the characters from a file (again, within a try ... catch block):
import java.io.FileReader;import java.io.IOException;public class FileReaderExample {public static void main(String[] args) {try {FileReader myReader = new FileReader("test.txt");int i;while ((i = myReader.read()) != -1)System.out.print((char)i);myReader.close();} catch (IOException e) {System.out.println("An error was thrown.");e.printStackTrace();}}}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours