FileWriter
FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
BufferedWriter
BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.
FileOutputStream
FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.
Files
Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file.
FileReader
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. It is character-oriented class which is used for file handling in java.
The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
The File class has many useful methods for creating and getting information about files. For example:
Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
File created: filename.txt
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Creating File objects only create files abstractly. It does not physically create a file in your folder/ directory. File objects only exist during run time. File objects are created to be used with other input/output classes like FileReader and PrintWriter.
To get more information about a file, use any of the File methods:
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
the output will be:
File name: filename.txt
Absolute path: C:\Users\rodzi\rodziah\FilesIO\filename.txt
Writeable: true
Readable true
File size in bytes 52
To delete a file in Java, use the delete() method:
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
The output will be:
Failed to delete the file.
You can also delete a folder. However, it must be empty:
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}
The output will be:
Failed to delete the folder.
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:
method Description
void close() It closes the stream, flushing it first.
void flush() It flushes the stream.
void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.
void write(int c) It writes a single character.
void write(String str, int off, int len) It writes a portion of a string.
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Successfully wrote to the file.
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.
import java.io.*; // Import the FileWriter class
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class UseFileWriterReader {
public static void main(String[] args) {
try {
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
// Creates a FileReader Object
FileReader fr = new FileReader(file);
int i;
// read from file
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
This
is
an
example
Use the Scanner class to read the contents of the text file we created in the previous chapter:
Method Description
public int nextInt() read an integer
public String next() read a word
public String nextLine() read the rest of current line
public float nextFloat() read a float public double nextDouble()
import java.io.File; // Import the File class
import java.io.FileNotFoundException; //Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFileScanner {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!
Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, etc. Which one to use depends on the Java version you're working with and whether you need to read bytes or characters, and the size of the file/lines etc.
Remember that if a file that you are opening with the PrintWriter object with the name already exists in the directory it will be deleted and a new empty file with the same name is created. It's often useful to be able to append data to an existing file rather than overwriting it. To append data in an existing file you can use FileWriter class.
// Appending Data to a file
import java.io.*; // Import the FileWriter class
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class useFileWriterReader {
public static void main(String[] args) {
try {
File file = new File("Hello1.txt");
// creates the file
if (file.exists()) {
System.out.println("File already exists.");
} else {
file.createNewFile();
System.out.println("File created: " + file.getName()); }
// creates a FileWriter Object
FileWriter fw = new FileWriter(file);
//Writes the content to the file
fw.write("Selangor\n");
fw.write("Perak\n");
fw.flush();
fw.close();
fw = new FileWriter(file, true);
PrintWriter out = new PrintWriter(fw);
out.println("Kedah");
out.close();
// Creates a FileReader Object
FileReader fr = new FileReader(file);
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
File already exists.
Selangor
Perak
Kedah
import java.io.*; // Import the FileWriter class
import java.util.Scanner;
public class useFileWriterReader {
public static void main(String[] args) {
try {
File file = new File("Countries.txt");
// creates the file
if (file.exists()) {
System.out.println("File already exists.");
createFileReader(file);
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
createFileWriter(file, str);
System.out.println("After add new data:");
createFileReader(file);
} else {
file.createNewFile();
System.out.println("File created: " + file.getName());
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public static void createFileReader(File file) throws IOException{
// Creates a FileReader Object
FileReader fr = new FileReader(file);
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
public static void createFileWriter(File file, String str) throws IOException{
// Creates a FileReader Object
FileWriter fw = new FileWriter(file,true);
PrintWriter out = new PrintWriter(fw);
// Append the name of ocean to the file
out.println(str);
// Close the file.
out.close();
}
}
Try compile and run this program to see the output. Study this code and compare with the previous program.