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();
  }
}
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

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

Popular Posts

  • 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 ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • 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...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk