🔏
Tech
  • 🟢App aspects
    • Software architecture
      • Caching
      • Anti-patterns
      • System X-ability
      • Coupling
      • Event driven architecture
        • Command Query Responsibility Segregation (CQRS)
        • Change Data Capture (CDC)
      • Distributed transactions
      • App dev notes
        • Architecture MVP
      • TEMP. Check list
      • Hexagonal arch
      • Communication
        • REST vs messaging
        • gRPC
        • WebSocket
      • Load balancers
      • Storage limits
      • Event storming
    • Authentication
    • Deployment strategy
  • Databases
    • Classification
    • DB migration tools
    • PostreSQL
    • Decision guidance
    • Index
      • Hash indexes
      • SSTable, LSM-Trees
      • B-Tree
      • Engines, internals
    • Performance
  • System design
    • Interview preparation
      • Plan
        • Instagram
        • Tinder
        • Digital wallet
        • Dropbox
        • Live video streaming
        • Uber
        • Whatsup
        • Tiktok
        • Twitter
        • Proximity service
    • Algorithms
    • Acronyms
  • 🟢Programming languages
    • Java
      • Features
        • Field hiding
        • HashCode() and Equals()
        • Reference types
        • Pass by value
        • Atomic variables
      • Types
      • IO / NIO
        • Java NIO
          • Buffer
          • Channel
        • Java IO: Streams
          • Input streams
            • BufferedInputStream
            • DataInputStream
            • ObjectInputStream
            • FilterInputStream
            • ByteArrayInputStream
        • Java IO: Pipes
        • Java IO: Byte & Char Arrays
        • Java IO: Input Parsing
          • PushbackReader
          • StreamTokenizer
          • LineNumberReader
          • PushbackInputStream
        • System.in, System.out, System.error
        • Java IO: Files
          • FileReader
          • FileWriter
          • FileOutputStream
          • FileInputStream
      • Multithreading
        • Thread liveness
        • False sharing
        • Actor model
        • Singleton
        • Future, CompletableFuture
        • Semaphore
      • Coursera: parallel programming
      • Coursera: concurrent programming
      • Serialization
      • JVM internals
      • Features track
        • Java 8
      • Distributed programming
      • Network
      • Patterns
        • Command
      • Garbage Collectors
        • GC Types
        • How GC works
        • Tools for GC
    • Kotlin
      • Scope functions
      • Inline value classes
      • Coroutines
      • Effective Kotlin
    • Javascript
      • Javascript vs Java
      • TypeScript
    • SQL
      • select for update
    • Python
      • __init.py__
  • OS components
    • Network
      • TCP/IP model
        • IP address in action
      • OSI model
  • 🟢Specifications
    • JAX-RS
    • REST
      • Multi part
  • 🟢Protocols
    • HTTP
    • OAuth 2.0
    • LDAP
    • SAML
  • 🟢Testing
    • Selenium anatomy
    • Testcafe
  • 🟢Tools
    • JDBC
      • Connection pool
    • Gradle
    • vim
    • git
    • IntelliJ Idea
    • Elastic search
    • Docker
    • Terraform
    • CDK
    • Argo CD
      • app-of-app setup
    • OpenTelemetry
    • Prometheus
    • Kafka
      • Consumer lag
  • 🟢CI
    • CircleCi
  • 🟢Platforms
    • AWS
      • VPC
      • EC2
      • RDS
      • S3
      • IAM
      • CloudWatch
      • CloudTrail
      • ELB
      • SNS
      • Route 53
      • CloudFront
      • Athena
      • EKS
    • Kubernetes
      • Networking
      • RBAC
      • Architecture
      • Pod
        • Resources
      • How to try
      • Kubectl
      • Service
      • Tooling
        • ArgoCD
        • Helm
        • Istio
    • GraalVM
    • Node.js
    • Camunda
      • Service tasks
      • Transactions
      • Performance
      • How it executes
  • 🟢Frameworks
    • Hibernate
      • JPA vs Spring Data
    • Micronaut
    • Spring
      • Security
      • JDBC, JPA, Hibernate
      • Transactions
      • Servlet containers, clients
  • 🟢Awesome
    • Нейробиология
    • Backend
      • System design
    • DevOps
    • Data
    • AI
    • Frontend
    • Mobile
    • Testing
    • Mac
    • Books & courses
      • Path: Java Concurrency
    • Algorithms
      • Competitive programming
    • Processes
    • Finance
    • Electronics
  • 🟢Electronics
    • Arduino
    • IoT
  • Artificial intelligence
    • Artificial Intelligence (AI)
  • 🚀Performance
    • BE
  • 📘Computer science
    • Data structures
      • Array
      • String
      • LinkedList
      • Tree
    • Algorithms
      • HowTo algorithms for interview
  • 🕸️Web dev (Frontend)
    • Trends
    • Web (to change)
  • 📈Data science
    • Time series
Powered by GitBook
On this page
  • FileWriter Example
  • Overwriting vs. Appending the File
  • FileWriter Character Encoding
  • write(int)
  • write(char[])
  • Write Performance
  • Transparent Buffering via BufferedWriter
  • flush()
  • Closing a FileWriter

Was this helpful?

  1. Programming languages
  2. Java
  3. IO / NIO
  4. Java IO: Files

FileWriter

PreviousFileReaderNextFileOutputStream

Last updated 2 years ago

Was this helpful?

The Java FileWriter class, java.io.FileWriter, makes it possible to write characters to a file. In that respect the Java FileWriter works much like the except that a FileOutputStream is byte based, whereas a FileWriter is character based. The FileWriter is intended to write text, in other words. One character may correspond to one or more bytes, depending on the character encoding scheme in use. The Java FileWriter class is a subclass of the class, by the way.

FileWriter Example

Here is a simple Java FileWriter example:

Writer fileWriter = new FileWriter("data\\filewriter.txt");

fileWriter.write("data 1");
fileWriter.write("data 2");
fileWriter.write("data 3");

fileWriter.close();

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to .

The FileWriter has other constructors too, letting you specify the file to write to in different ways. Look in the official JavaDoc for more detailed info.

Overwriting vs. Appending the File

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file. You decide that by choosing what FileWriter constructor you use.

The FileWriter constructor taking just one parameter, the file name, will overwrite any existing file:

Writer fileWriter = new FileWriter("c:\\data\\output.txt");

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true);  //appends to file

Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file

FileWriter Character Encoding

The FileWriter assumes that you want to encode the bytes to the file using the default character encoding for the computer your application is running on. This may not always be what you want, and you cannot change it!

write(int)

The Java FileWriter write(int) method writes the lower 16 bit of the int to the destination the FileWriter is connected to, as a single character. Here is an example of writing a single character to a Java FileWriter:

FileWriter fileWriter = new FileWriter("data/output.txt");

fileWriter.write('A');

write(char[])

The Java FileWriter also has a write(char[]) method which can write an array of characters to the destination the FileWriter is connected to. The write(char[]) method returns the number of characters actually written to the FileWriter. Here is an example of writing an array of chars to a Java FileWriter:

FileWriter fileWriter = new FileWriter("data/output.txt");

char[] chars = new char[]{'A','B','C','D','E'};
fileWriter.write(chars);

Write Performance

It is faster to write an array of characters to a Java FileWriter than writing one character at a time. The speedup can be quite significant - up to 10 x higher or more. Therefore it is recommended to use the write(char[]) methods whenever possible.

The exact speedup you get depends on the underlying OS and hardware of the computer you run the Java code on. The speedup depends on issues like memory speed, hard disk speed and buffer sizes etc.

Transparent Buffering via BufferedWriter

int bufferSize = 8 * 1024;

Writer writer =
    new BufferedWriter(
          new FileWriter("c:\\data\\output-file.txt"),
              bufferSize
    );

flush()

The Java FileWriter's flush() method flushes all data written to the FileWriter to the underlying file. The data might be buffered in OS memory somewhere, even if your Java code has written it to the FileWriter. By calling flush() you can assure that any buffered data will be flushed (written) to disk. Here is an example of flushing data written to a Java FileWriter by calling its flush() method:

fileWriter.flush();

Closing a FileWriter

When you are finished writing characters to a Java FileWriter you should remember to close it. Closing a FileWriter is done by calling its close() method. Here is how closing a Java FileWriter looks:

fileWriter.close();
try(FileWriter fileWriter =
    new FileWriter("data\\filewriter.txt") ){

    fileWriter.write("data 1");
    fileWriter.write("data 2");
    fileWriter.write("data 3");

}

Notice how there is no longer any explicit close() method call to the FileWriter instance. The try-with-resources construct takes care of that.

If you want to specify a different character encoding scheme, don't use a FileWriter. Use an on a FileOutputStream instead. The OutputStreamWriter lets you specify the character encoding scheme to use when writing bytes to the underlying file.

You can get transparent buffering of bytes written to a Java FileWriter by wrapping it in a . All bytes written to the BufferedWriter will first get buffered inside an internal byte array in the BufferedWriter. When the buffer is full, the buffer is flushed to the underlying FileWriter all at once. Here is an example of wrapping a Java FileWriter in a BufferedWriter:

You can read more about the BufferedWriter in my .

You can also use the construct introduced in Java 7. Here is how to use and close a FileWriter looks with the try-with-resources construct:

🟢
FileOutputStream
Java Writer
Java IO Exception Handling
OutputStreamWriter
Java BufferedWriter
BufferedWriter tutorial
try-with-resources