Preface
FileWriter
is a convenient class specially used to write characters to files. It inherits fromOutputStreamWriter
, belongs to a part of the character stream class, suitable for processing writing operations of text files.
1. FileWriter Overview
`FileWriter` is mainly used to write character data into files. It is automatically created if the file does not exist; if the file already exists, the contents of the file are overwritten by default. Compared with byte streams, `FileWriter` is more suitable for processing text files and is more efficient to use.
Basic constructor:
FileWriter writer = new FileWriter("");
-
: The destination file path. If the file does not exist,
FileWriter
Will be created automatically.
Use append mode:
FileWriter writer = new FileWriter("", true);
intrue
It means that the file is opened in append mode, and the data will be appended to the end of the file and will not overwrite the existing content.
2. Basic usage of FileWriter
Write simple text content into the file:
import ; import ; public class FileWriterExample { public static void main(String[] args) { try (FileWriter writer = new FileWriter("E:/software/test/")) { ("Hello, FileWriter!\n"); ("This is a new line.\n"); } catch (IOException e) { (); } } }
Key points:
-
write()
Method: Used to write strings to a file. Can write any character data. -
try-with-resources
: Automatically manage resources to ensure that the stream can be automatically closed after file writing is completed without manual calls.close()
。 - If you do not specify a specific path, the generated file is in the same directory as src.
Output file `` content:
Hello, FileWriter!
This is a new line.
Example of append mode
If you do not want to overwrite the original content and want to add new content at the end of the file, you can use the append mode:
import ; import ; public class FileWriterExample { public static void main(String[] args) { try (FileWriter writer = new FileWriter("E:/software/test/",true)) { // ("Hello, FileWriter!\n"); // ("This is a new line.\n"); ("This text is appended.\n"); } catch (IOException e) { (); } } }
The content of the file will be updated:
Hello, FileWriter!
This is a new line.
This text is appended.
3. Advanced usage: character array and partial character writing
In addition to writing strings,FileWriter
You can also write to a character array.
Write character array
public static void main(String[] args) { try (FileWriter writer = new FileWriter("E:/software/test/",true)) { // ("Hello, FileWriter!\n"); // ("This is a new line.\n"); // ("This text is appended.\n"); char[] data = "FileWriter example with char array.".toCharArray(); (data); } catch (IOException e) { (); } }
The text content is updated as follows:
Hello, FileWriter!
This is a new line.
This text is appended.FileWriter example with char array.
Write some characters
If you want to write only a portion of the characters in the array, you can specify the offset and the length of the write:
public static void main(String[] args) { try (FileWriter writer = new FileWriter("E:/software/test/",true)) { // ("Hello, FileWriter!\n"); // ("This is a new line.\n"); // ("This text is appended.\n"); // char[] data = "FileWriter example with char array.".toCharArray(); // (data); // ("\n"); char[] data = "Partial char array example.".toCharArray(); (data, 8, 10); // Start with index 8 and write 10 characters ("\n"); } catch (IOException e) { (); } }
The text content is updated as follows:
Hello, FileWriter!
This is a new line.
This text is appended.FileWriter example with char array.
char array
4. FileWriter works with BufferedWriter
AlthoughFileWriter
Very convenient, but its performance may be affected when processing large amounts of data, as it is written character by character. If you need to efficiently process large data volumes, it is recommended toBufferedWriter
Use with combination.
public static void main(String[] args) { try (BufferedWriter writer = new BufferedWriter(new FileWriter("E:/software/test/"))) { ("BufferedWriter is much faster."); (); // Write newline characters ("BufferedWriter is much faster."); } catch (IOException e) { (); } }
Text content:
BufferedWriter is much faster.
BufferedWriter is much faster.
Why use `BufferedWriter`?
-
buffer:
BufferedWriter
Provides a buffer that reduces the number of actual file written to improve performance. -
More efficient processing: When writing a large amount of data,
BufferedWriter
perform better.
5. Control refresh: `flush()` method
File writing is usually written to the buffer in memory first, rather than directly to disk. To ensure that data is written to the file immediately, you can useflush()
method, it will force the data in the buffer to disk.
public static void main(String[] args) { try (BufferedWriter writer = new BufferedWriter(new FileWriter("E:/software/test/"))) { ("This data will be flushed."); (); // Force the data in the buffer to disk } catch (IOException e) { (); } }
When to use `flush()`?
If you want to make sure that the data is written to the file before the file stream is closed, you can callflush()
method. Usually no manual call is required, because inclose()
The buffer will be automatically refreshed.
6. Frequently Asked Questions and Precautions
1. The file does not exist
FileWriter
The target file will be automatically created (if the file does not exist). But if there is a problem with the specified path (such as the folder does not exist), it will be thrownIOException
。
2. Coding issues
FileWriter
The default character encoding of the system is used by default. If you need to specify the encoding, you can useOutputStreamWriter
,For example:
import ; import ; import ; import ; public class FileWriterExample { public static void main(String[] args) { try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("E:/software/test/"), StandardCharsets.UTF_8)) { ("This is UTF-8 encoded text."); } catch (IOException e) { (); } } }
7. Similarities and similarities between FileWriter, BufferedWriter and OutputStreamWriter
characteristic | FileWriter | OutputStreamWriter | BufferedWriter |
---|---|---|---|
Basic functions | Write character data directly to the file | Convert a character stream to a byte stream and write to a file | Add buffering to character streams to reduce actual write operations |
Inheritance relationship | Inherited fromOutputStreamWriter
|
Inherited fromWriter , wrap the byte output stream |
Inherited fromWriter , wrap character output stream |
Coding control | System encoding is used by default | Character encoding can be specified manually | Rely on packagedWriter
|
performance | Low performance, no buffering mechanism | Low performance, no buffering mechanism | High performance, using buffering mechanism |
Whether to buffer | No buffering | No buffering | Use buffers to improve performance |
Applicable scenarios | Simple file writing operation | Need to handle character encoding file writing | Need to efficiently write large or frequent small data |
Example of a combination of BufferedWriter and OutputStreamWriter:
public static void main(String[] args) { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:/software/test/"), StandardCharsets.UTF_8))) { ("This is BufferedWriter and OutputStreamWriter text."); } catch (IOException e) { (); } }
8. Summary
-
FileWriter
Suitable for simple file writing scenarios, does not support encoding control, and does not have a buffering mechanism. -
OutputStreamWriter
It is mainly used to convert character streams into byte streams, and supports manual character encoding. It is a bridge between character streams and byte streams. -
BufferedWriter
Reduce actual I/O operations by adding a buffering mechanism and improve performance, suitable for frequent small data writing scenarios.
This is the end of this article about the detailed explanation of the usage of FileWriter in Java. For more detailed explanation of the usage of FileWriter in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!