Task

Load the entire contents of some text file as a single string variable.

If applicable, discuss: encoding selection, the possibility of memory-mapping.

Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.




/* NetRexx */
options replace format comments java crossref symbols nobinary
 
parse arg inFileName .
 
if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json'
fileContents = slurp(inFileName)
say fileContents
 
return
 
-- Slurp a file and return contents as a Rexx string
method slurp(inFileName) public static returns Rexx
 
  slurped = Rexx null
  slurpStr = StringBuilder()
  ioBuffer = byte[1024]
  inBytes = int 0
 
  do
    inFile = File(inFileName)
    inFileIS = BufferedInputStream(FileInputStream(inFile))
 
    loop label ioLoop until inBytes = -1
      slurpStr.append(String(ioBuffer, 0, inBytes))
      inBytes = inFileIS.read(ioBuffer)
      end ioLoop
 
  catch exFNF = FileNotFoundException
    exFNF.printStackTrace
  catch exIO = IOException
    exIO.printStackTrace
  finally
    do
      inFileIS.close()
    catch ex = IOException
      ex.printStackTrace
    end
  end
 
  slurped = Rexx(slurpStr.toString)
 
  return slurped
 