[post-views]
In this lesson, you will learn.
Writing to a file in Java can be achieved using several APIs provided by Java.
Below, we will cover a few common methods to write a file in Java using the FileWriter
and BufferedWriter
class.
FileWriter creates a Writer that you can use to write to a file and is a subclass of OutputStreamWriter
.
The four commonly used constructors are shown here:
1. FileWriter(String fileName): Creates a FileWriter
object given a name of the file. It will overwrite the content of the file if it exists.
2. FileWriter(String fileName, boolean append): Creates a FileWriter
object given a file name with an option to append. If append
is true, then data will be written to the end of the file rather than the beginning.
3. FileWriter(File file): Creates a FileWriter
object given a File
object. This constructor will also overwrite the existing file.
4. FileWriter(File file, boolean append): Similar to the second constructor but uses a File
object. It allows appending if the boolean append
is set to true.
package filewriting;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample1 {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("src/filewriting/example1.txt");
writer.write("Hello, this is text written to a file.");
writer.write("nNandini");
writer.write("nRam");
System.out.println("The file writing operation completed!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
The file writing operation completed!
This constructor overwrites example.txt
if it exists or creates a new file if it doesn’t.
package filewriting;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample2 {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("src/filewriting/example2.txt",true);
writer.write("nAppending this line to the file.");
writer.write("nNandini");
writer.write("nRam");
System.out.println("The file writing operation completed!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
The file writing operation completed!
This code appends text to the existing example2.txt
file. If the file does not exist, it creates a new file.
package filewriting;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample3 {
public static void main(String[] args) {
File file = new File("src/filewriting/example3.txt");
try {
FileWriter writer = new FileWriter(file);
writer.write("Writing to a file using File object.");
System.out.println("The file writing operation completed!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This approach uses a File
object to specify the file path, which is useful when the file object is already available from previous operations.
BufferedWriter
writes text to a character-output stream, buffering characters to provide for the efficient writing of single characters, arrays, and strings.
BufferedWriter
itself does not directly deal with file paths or files; it wraps another Writer
object. The primary constructors for BufferedWriter
are:
1. BufferedWriter(Writer out): Creates a buffered character-output stream that uses the default size for an output buffer.
2. BufferedWriter(Writer out, int sz): Creates a buffered character-output stream that uses the specified size for an output buffer.
BufferedWriter
is used with a FileWriter
to take advantage of both buffering and file writing capabilities.
package filewriting;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample1 {
public static void main(String[] args) {
try {
//creates example.txt in project directory
BufferedWriter writer = new BufferedWriter
(new FileWriter("example.txt"));
writer.write("Hello, this is text written to a file.");
writer.newLine();
writer.write("This text is on a new line.");
System.out.println("The file writing operation completed!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
The file writing operation completed!
In this example, BufferedWriter
is used with a specified buffer size. Adjusting the buffer size can improve performance depending on the size of data being written and system specifics.
package filewriting;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample2 {
public static void main(String[] args) {
// This is actually the default size, but you can choose your own
int bufferSize = 8192; //No of Characters
try {
BufferedWriter writer = new BufferedWriter
(new FileWriter("example1.txt"), bufferSize);
writer.write("Hello, this text uses a custom buffer size.");
writer.newLine();
writer.write("More efficient for large amounts of data.");
System.out.println("The file writing operation completed!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
The file writing operation completed!
In this example, a larger buffer size may be beneficial if you’re writing large amounts of data at once. It reduces the number of physical disk writes by storing more data in memory before flushing it to disk.
Using BufferedWriter
over FileWriter
directly provides a significant performance advantage when writing character data to a file, especially in cases where many small write operations occur.
The buffering minimizes the number of I/O operations, each of which could be costly due to the overhead of interacting with the disk.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.