juan_gandhi: (VP)
[personal profile] juan_gandhi

  def using[T](file:File)(f: FileInputStream => T): Try[T] = Try {
    val in = new FileInputStream(file)
    (Try(f(in)), Try(in.close))._1
  }.flatten

  def startsWith(prefix: Array[Byte])(file: File):Boolean =
    using (file) (in => prefix forall (in.read ==)) filter identity isSuccess


What happens here. I want to check if a file starts with these bytes (usually, "%PDF".getBytes).

I have function using that takes a file, then takes a function that converts a stream into something, opens the file, feeds the stream to the function, then always closes the file, returning a failure something went wrong.

In startsWith I get a prefix and a file; on this file I call the function that reads the stream and compares its bytes with the bytes of prefix; the result will be Try[Boolean]; I filter it, so that Success(false) will turn into Failure; then I check if it's still a success.

Obvious and funny; and yes, we use Java io library here, unfortunately.
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

June 2025

S M T W T F S
1 2345 6 7
8 9 10 11 121314
15161718 1920 21
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 26th, 2025 02:18 pm
Powered by Dreamwidth Studios