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

Friday, May 9, 2014

Approaches to read files in Java

 May 09, 2014     Java     No comments   

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

Using InputStreamReader with a BufferedReader

Refer the example function below. FileInputStream is the byte stream here reading raw bytes from the file. InputStreamReader is a bridge which converts the raw bytes into characters using the specified charset. The InputStreamReader is a unbuffered stream. To make the program efficient for reading characters, lines etc. it needs to be wrapped with a buffered stream like the BufferedReader.
public static String readFileToString(String fileName) {
  StringBuffer buffer = new StringBuffer();
  BufferedReader in = null;
  try {
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8);
    in = new BufferedReader(reader);
        String line = null;
        while ((line = in.readLine()) != null)
        {
            buffer.append(line + System.getProperty("line.separator"));
        }
  } catch ( IOException e ) {
    e.printStackTrace();
  }
  finally {
    try {
      if ( in != null ) in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return buffer.toString();
}

Using FileReader with a BufferedReader

Refer the example function below. FileReader is a convenience class for reading character files. FileReader assumes the default character encoding and byte buffer size. FileReader is unbuffered and we need to wrap it in a buffered stream to make the program more efficient for reading.
public static String readFileToString1(String fileName) {
  StringBuffer buffer = new StringBuffer();
  BufferedReader in = null;
  try {
    // Using FileReader doesn't support encoding
    in = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = in.readLine()) != null)
        {
            buffer.append(line + System.getProperty("line.separator"));
        }
  } catch ( IOException e ) {
    e.printStackTrace();
  }
  finally {
    try {
      if ( in != null ) in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return buffer.toString();
}

Using InputStreamReader with a Scanner

Refer the example function below. FileInputStream is the byte stream here reading raw bytes from the file. InputStreamReader is a bridge which converts the raw bytes into characters using the specified charset. The InputStreamReader is a unbuffered stream. In this example, we have used the Scanner instead of BufferedReader. Scanner has the capability to parse the input stream for primitive types, tokens based on regular expressions and delimiters. One important thing to note is BufferedReader is thread safe whereas Scanner is not thread safe and synchronization needs to be handled by the application program.
public static String readFileToString4(String fileName) {
  StringBuffer buffer = new StringBuffer();
  Scanner in = null;
  try {
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8);
    in = new Scanner(reader);
    while ( in.hasNextLine() ) {
      buffer.append(in.nextLine() + System.getProperty("line.separator"));
    }
  } catch ( IOException e ) {
    e.printStackTrace();
  }
  finally {
    if ( in != null ) in.close();
  }
  return buffer.toString();
}

Using Files for Java7

Java7 has introduced the new file I/O package which provides the Files API to make reading files much simpler. Refer example below.
// Works only with Java7
public static String readFileToString(String fileName) {
  byte[] buffer = null;
  try {
    buffer = Files.readAllBytes(Paths.get(fileName));
  } catch (IOException e) {
    e.printStackTrace();
  }
  try {
    return new String(buffer, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  }
  return null;
}
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