DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Trending

  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • Batching Strategies: Throughput vs Latency in Practice
  • How to Format Articles for DZone
  • GET, POST, PUT, DELETE: Choosing HTTP Verbs in a Real .NET Core Web API, Not Just by the Textbook

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

Search in Big Files Via MappedByteBuffer

Learn more about search in big files via MappedByteBuffer.

By 
Anghel Leonard
DZone Core CORE ·
Dec. 04, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Coffee and saucer

Learn more about search in big files via MappedByteBuffer.

This application is useful for searching in big files that don't fit well for BufferedReader,  Files.readAllLines(), Files.lines(), and Scanner.

The solution that we'll talk about here is based on Java NIO.2, MappedByteBuffer, and FileChannel. This solution opens a memory-mapped byte buffer (MappedByteBuffer) from a FileChannel on the given file. We traverse the fetched byte buffer and look for matches with the searched string (this string is converted into a byte[] and searching take place byte by byte).

For relatively small files, it is faster to load the entire file into memory (if RAM allows it). For large/huge files, it is faster to load and process the files in chunks (for example, a chunk of 5 MB). Once we have loaded a chunk, we have to count the number of occurrences of the searched string. We store the result and pass it to the next chunk of data. We repeat this until the entire file has been traversed.

Let's take a look at the core lines of this implementation (take a look at the source code bundled with this book for the complete code):

private static final long MAP_SIZE = 5242880; // 5 MB in bytes

public static long countOccurrences(Path path, String text)
                                           throws IOException {

   final byte[] texttofind = text.getBytes(StandardCharsets.UTF_8);
   long count = 0;

   try (FileChannel fileChannel = FileChannel.open(path,
                                           StandardOpenOption.READ)) {
      long position = 0;
      long length = fileChannel.size();

      while (position < length) {
         long remaining = length - position;
         long bytestomap = (long) Math.min(MAP_SIZE, remaining);

         MappedByteBuffer mbBuffer = fileChannel.map(
                          MapMode.READ_ONLY, position, bytestomap);
         long limit = mbBuffer.limit();
         long lastSpace = -1;
         long firstChar = -1;
         while (mbBuffer.hasRemaining()) {
            // code omitted for brevity available on GitHub
            ...
         }
      }
   }

   return count;
}


This solution is extremely fast because the file is read directly from the operating system's memory without having to be loaded into the JVM. The operations take place at the native level, called the operating system level. Note that this implementation works only for the UTF-8 charset, but it can be adapted for other charsets as well.

The complete application is available on GitHub.

If you enjoyed this article, then I'm sure you will love Chapter 6 from Java Coding Problem. This chapter is dedicated to file/folders manipulation in Java.

Further Reading

Comparing Files in Java

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook