StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Sunday, June 15, 2014

Approaches to write files in Java

 June 15, 2014     Java     No comments   

This article describes some of the common approaches to write files in Java.

Using OutputStreamWriter with a BufferedReader

Refer the example function below. FileOutputStream is the byte stream here capable of writing raw bytes to the file. OutputStreamWriter is a bridge which converts characters into raw bytes using the specified charset. The OutputStreamWriter is a unbuffered stream. To make the program efficient for writing characters, lines etc. it needs to be wrapped with a buffered stream like the BufferedWriter.
public static void writeStringToFile1(String str) { 
  BufferedWriter writer = null;
  try {
    File file = new File("output/test1.txt");
    if ( ! file.exists() )
      file.createNewFile();

    FileOutputStream fos = new FileOutputStream(file);
    OutputStreamWriter out = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
    writer = new BufferedWriter(out);
    writer.write(str);
    writer.flush();

  } catch ( IOException e ){
    e.printStackTrace();
  }
  finally {
    try {
      if ( writer != null )
        writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Using FileWriter with a BufferedWriter

Refer the example function below. FileWriter is a convenience class for writing character files. FileWriter assumes the default character encoding. FileWriter is unbuffered and we need to wrap it in a buffered stream to make the program more efficient for reading.
public static void writeToFile2(String str) { 
  BufferedWriter out = null;
  try {
    File file = new File("output/test2.txt");
    if ( ! file.exists() )
      file.createNewFile();

    FileWriter writer = new FileWriter(file);
    out = new BufferedWriter(writer);
    out.write(str);
    out.flush(); 
  } catch ( IOException e ){
    e.printStackTrace();
  }
  finally {
    if ( out != null ) {
      try {
        out.close();
      } catch ( IOException e ){
        e.printStackTrace();
      }
    }
  }
}

Using PrintWriter with a BufferedWriter

Refer the example function below. PrintWriter has the capability to print formatted representations of objects to a text output stream.
public static void writeToFile3(String str) { 
  PrintWriter out = null;
  try {
    File file = new File("output/test3.txt");
    if ( ! file.exists() )
      file.createNewFile();

    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    out = new PrintWriter(writer);
    out.println(str);
    // Write formatted output
    out.println(true);
    out.println(123.00);
    out.printf("%5d\n", 100);
    out.flush();

  } catch ( IOException e ){
    e.printStackTrace();
  }
  finally {
    if ( out != null ) {
      out.close();
    }
  }
}

Using Files for Java7

Java7 has introduced the new file I/O package which provides the Files API to make writing files much simpler. Refer example below.
public static void writeUsingJava7(String str) {
  try {
    Files.write(Paths.get("output/test10.txt"), 
        str.getBytes(), 
        StandardOpenOption.CREATE);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk