🔏
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
  • Java FileOutputStream Example
  • FileOutputStream Constructors
  • write()
  • Writing Byte Arrays
  • Write Performance
  • Transparent Buffering via BufferedOutputStream
  • flush()
  • Closing a FileOutputStream
  • Convert FileOutputStream to Writer

Was this helpful?

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

FileOutputStream

PreviousFileWriterNextFileInputStream

Last updated 2 years ago

Was this helpful?

Java FileOutputStream Example

Here is a simple Java FileOutputStream example:

OutputStream output = new FileOutputStream("c:\\data\\output-text.txt");

while(moreData) {
  int data = getMoreData();
  output.write(data);
}
output.close();

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to . There is also an example of better exception handling at the bottom of this tutorial, in the section about closing a Java FileOutputStream.

FileOutputStream Constructors

The Java FileOutputStream class contains a set of different useful constructors. I will cover the most commonly used constructors here.

The first constructor takes a String which contains the path of the file to write to. Here is an example:

String path = "C:\\users\\jakobjenkov\\data\\datafile.txt";

FileOutputStream output = new FileOutputStream(path);

Notice the path String. It needs double backslashes (\\) to create a single backslash in the String, because backslash is an escape character in Java Strings. To get a single backslash you need to use the escape sequence \\.

On unix the file path could have looked like this:

String path = "/home/jakobjenkov/data/datafile.txt";
String path = "C:\\users\\jakobjenkov\\data\\datafile.txt";
File   file = new File(path);

FileOutputStream output = new FileOutputStream(file);

Overwriting vs. Appending the File

When you create a Java FileOutputStream pointing to a file that already exists, you can decide if you want to overwrite the existing file, or if you want to append to the existing file. You decide that based on which of the FileOutputStream constructors you choose to use.

This constructor which takes just one parameter, the file name, will overwrite any existing file:

OutputStream output = new FileOutputStream("c:\\data\\output-text.txt");

There is a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append to the file or not. Thus, a value of true means that you want to append to the file, whereas a value of false means you want to overwrite the file. Here are two Java FileOutputStream constructor examples:

OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", true); //append

OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", false); //overwrite

When you leave out the second boolean parameter and thus just use the constructor that takes a file path, the default mode is to overwrite any existing file on the given path.

write()

To write data to a Java FileOutputStream you can use its write() method. The write() method takes an int which contains the byte value of the byte to write. Thus, only the lower 8 bit of the passed int actually gets written to the FileOutputStream destination. Here is an example of writing data to a Java FileOutputStream using its write() method:

OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

outputStream.write(123);

This example writes the byte value 123 to the given Java FileOutputStream.

How int (4 bytes) is truncated to bute (1 byte) while writing to stream

write() method in FileOutputStream takes an int but truncates the first 3 bytes and writes the byte to stream. If a file contains characters whose ASCII value is more than 127 and bytes are read from it and then written to output stream(another text file) how will it display it because in Java bytes can have a max value of +127.

If a text file(input.text) has character '›' whose ASCII value is 155. An input stream,input, reads from it : int in= new FileInputStream("input.txt").read();//in = 155

Now it writes to another text file(output.txt)

new FileOutputStream("output.txt").write(in);

Answer:

I think your confusion is caused by the fact that specs for character sets typically take the view that bytes are unsigned, while Java treats bytes as signed.

In fact 155 as an unsigned byte is -101 as a signed byte. (256 - 101 == 155). The bit patterns are identical. It is just a matter of whether you think of them as signed or unsigned.

How the truncation is coded is implementation specific. But there is no loss of information ... assuming that you had an 8-bit code in the first place.

Writing Byte Arrays

OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

byte bytes =  new byte[]{1,2,3,4,5};

outputStream.write(bytes);

Write Performance

It is faster to write an array of bytes to a Java FileOutputStream than writing one byte at a time. The speedup can be quite significant - up to 10 x higher or more. Therefore it is recommended to use the write(byte[]) 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.

Transparent Buffering via BufferedOutputStream

int bufferSize = 8 * 1024;
FileOutputStream output = new BufferedOutputStream(
                      new FileOutputStream("c:\\data\\output-file.txt"),
                          bufferSize
);

flush()

When you write data to a Java FileOutputStream the data may get cached internally in the memory of the computer and written to disk at a later time. For instance, every time there is X amount of data to write, or when the FileOutputStream is closed.

If you want to make sure that all written data is written to disk without having to close the FileOutputStream you can call its flush() method. Calling flush() will make sure that all data which has been written to the FileOutputStream so far, is fully written to disk too. Here is an example of calling the Java FileOutputStream flush() method:

OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

byte bytes =  new byte[]{1,2,3,4,5};

outputStream.write(bytes);

outputStream.flush()

Closing a FileOutputStream

Like any other OutputStream a FileOutputStream instance needs to be closed after use. You do so by calling its close() method. Here is an example of closing a Java FileOutputStream by calling its close() method:

OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

outputStream.write(123);

outputStream.close();
try( OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt") ) {
    outputStream.write(123);
}

Notice how the FileOutputStream is declared inside the parentheses following the try keyword. All resources declared inside these parentheses will be closed automatically once the program flow exits the try block, regardless of whether an exception is thrown or not. In other words, the FileOutputStream close() will be called automatically for you.

Convert FileOutputStream to Writer

FileOutputStream outputStream       = new FileOutputStream("c:\\data\\output.txt");
Writer       outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");

The second FileOutputStream constructor takes a object which points to the file in the file system. Here is an example:

Since the Java FileOutputStream is a subclass of , you can write arrays of bytes to the FileOutputStream too, instead of just a single byte at a time. Here is an example of writing an array of bytes to a Java FileOutputStream :

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

You can more about the BufferedOutputStream in my .

Unfortunately, if an exception is thrown during the write() call in the example above, that exception will cause the program flow to break before the close() method is called. Therefore it is better to close a Java FileOutputStream using the construct. Here is an example of closing a Java FileOutputStream using the try-with-resources construct:

The Java FileOutputStream is a byte based stream. You can convert a FileOutputStream to a character based Writer using the class. Here is an example of converting a Java FileOutputStream to a Writer using OutputStreamWriter:

You can read more about how to use the OutputStreamWriter including how to set the character encoding to use when converting characters to bytes in my .

🟢
Java IO Exception Handling
Java File
Link
OutputStream
Java BufferedOutputStream
BufferedOutputStream tutorial
Java try with resources
Java OutputStreamWriter
OutputStreamWriter tutorial