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;
}
  • 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