Efficiently read part of a file by seek offsets

Open
#107 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
38/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
clojure, java
Domain
tooling

Research direction

No repository file or test is named. Start by locating the existing file-reading entry point, then compare its behavior with the proposed java.nio SeekableByteChannel approach and clarify whether start and end refer to characters or bytes. Done means the requested file slice is read without loading the entire file.

Written by the indexing model from the issue text.

Description

It would be nice to read a slice of a file, based on the start & end char indices.

chatgpt attempt, seems to work:

Yes, there is a more efficient way to handle large files by reading only the necessary parts of the file instead of slurping the entire content. You can accomplish this using Java's java.nio.file API. Here is a way to do this using interop:

(defn lazy-substring-of-file [filename start end]
  (let [path (java.nio.file.Paths/get filename (into-array String []))
        options (into-array java.nio.file.OpenOption [java.nio.file.StandardOpenOption/READ])
        fc (.newByteChannel java.nio.file.Files path options)
        bb (java.nio.ByteBuffer/allocate (- end start))]
    (.position fc start)
    (.read fc bb)
    (.close fc)
    (String. (.array bb) "UTF-8")))

In this function:

  • java.nio.file.Paths/get is used to get a java.nio.file.Path object from the filename.
  • java.nio.file.Files/newByteChannel is used to create a new java.nio.channels.SeekableByteChannel to the file.
  • java.nio.ByteBuffer/allocate is used to create a ByteBuffer of the right size.
  • .position is used to set the read position of the byte channel.
  • .read is used to read the right amount of bytes from the file into the ByteBuffer.
  • String. (.array bb) "UTF-8" is used to create a new string from the ByteBuffer.

This function avoids reading the whole file into memory by only reading the necessary bytes. It works best when start and end are relatively small compared to the size of the file.

Dominant language
Clojure
Stars
221
Forks
52
PR merge metrics
No merged PRs in 30d

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from babashka/fs

All issues in babashka/fs

Similar issues

More Clojure issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.