FileOutputStream in Java



Introduction:

Java provides a robust set of APIs for file handling, and FileOutputStream is a key player when it comes to writing data to files. In this blog post, we will delve into the intricacies of FileOutputStream and explore 10 different code examples to illustrate its various functionalities.

Example 1: Basic FileOutputStream


import java.io.FileOutputStream;
import java.io.IOException;

public class BasicFileOutput {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String data = "Hello, FileOutputStream!";
byte[] byteArray = data.getBytes();
fos.write(byteArray);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: This example demonstrates the fundamental usage of FileOutputStream to write a simple string to a file named "output.txt".

Example 2: Writing Byte Array


import java.io.FileOutputStream;
import java.io.IOException;

public class ByteArrayOutput {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.bin")) {
byte[] byteArray = {65, 66, 67, 68, 69}; // ASCII values
fos.write(byteArray);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Here, we write a byte array to a binary file, representing ASCII values.





Example 3: Writing Partial Data


import java.io.FileOutputStream;
import java.io.IOException;

public class PartialDataOutput {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("partial_output.txt")) {
String data = "Java FileOutputStream Example";
byte[] byteArray = data.getBytes();
fos.write(byteArray, 0, 10); // Writes only the first 10 characters
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: This example shows how to write only a portion of the byte array to the file.

Example 4: Appending Data to a File


import java.io.FileOutputStream;
import java.io.IOException;

public class AppendToFile {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.txt", true)) {
String data = "\nAppending data to file.";
byte[] byteArray = data.getBytes();
fos.write(byteArray);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Demonstrates how to open a file in append mode and add new content.





Example 5: Using BufferedOutputStream


import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutput {
public static void main(String[] args) {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("buffered_output.txt"))) {
String data = "Using BufferedOutputStream in Java.";
byte[] byteArray = data.getBytes();
bos.write(byteArray);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Shows how to use `BufferedOutputStream` for improved performance in file writing.

Example 6: Writing Data Asynchronously


import java.io.FileOutputStream;
import java.io.IOException;

public class AsyncOutput {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("async_output.txt")) {
String data = "Asynchronous FileOutputStream Example.";
byte[] byteArray = data.getBytes();
fos.write(byteArray);
fos.flush(); // Flushes the stream
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Demonstrates asynchronous file writing using `flush()`.

Example 7: Writing Data with DataOutputStream


import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputExample {
public static void main(String[] args) {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data_output.txt"))) {
int intValue = 42;
dos.writeInt(intValue);
dos.writeUTF("DataOutputStream Example");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Illustrates how to use `DataOutputStream` for writing primitive data types.





Example 8: Writing Objects with ObjectOutputStream


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Person implements Serializable {
String name;
int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

public class ObjectOutputExample {
public static void main(String[] args) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
Person person = new Person("John Doe", 30);
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Demonstrates how to use `ObjectOutputStream` to write objects to a file.

Example 9: Writing to Multiple Files


import java.io.FileOutputStream;
import java.io.IOException;

public class MultipleFilesOutput {
public static void main(String[] args) {
try (FileOutputStream fos1 = new FileOutputStream("file1.txt");
FileOutputStream fos2 = new FileOutputStream("file2.txt")) {

fos1.write("Data for file 1".getBytes());
fos2.write("Data for file 2".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Shows how to write to multiple files using separate `FileOutputStream` instances.

Example 10: Handling Exceptions


import java.io.FileOutputStream;
import java.io.IOException;

public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("nonexistent_dir/output.txt");
String data = "Handling FileOutputStream Exceptions.";
byte[] byteArray = data.getBytes();
fos.write(byteArray);
fos.close(); // Close the stream explicitly
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Demonstrates proper exception handling when dealing with FileOutputStream.

Conclusion:

In this comprehensive guide, we explored various aspects of FileOutputStream in Java with 10 code examples. From basic file writing to advanced topics like object serialization, understanding these concepts equips you with the knowledge to handle a wide range of file output operations in your Java applications.



Post a Comment

Previous Post Next Post