class File

Overview

A File instance represents a file entry in the local file system and allows using it as an IO.

file = File.new("path/to/file")
content = file.gets_to_end
file.close

# Implicit close with `open` and a block:
content = File.open("path/to/file") do |file|
  file.gets_to_end
end

# Shortcut of the above:
content = File.read("path/to/file")

# Write to a file by opening with a "write mode" specified.
File.open("path/to/file", "w") do |file|
  file.print "hello"
end
# Content of file on disk will now be "hello".

# Shortcut of the above:
File.write("path/to/file", "hello")

See new for various options mode can be.

Temporary Files

Every tempfile is operated as a File, including initializing, reading and writing.

tempfile = File.tempfile("foo")

File.size(tempfile.path)                   # => 6
File.info(tempfile.path).modification_time # => 2015-10-20 13:11:12 UTC
File.exists?(tempfile.path)                # => true
File.read_lines(tempfile.path)             # => ["foobar"]

Files created from tempfile are stored in a directory that handles temporary files (Dir.tempdir):

File.tempfile("foo").path # => "/tmp/foo.ulBCPS"

It is encouraged to delete a tempfile after using it, which ensures they are not left behind in your filesystem until garbage collected.

tempfile = File.tempfile("foo")
tempfile.delete

Included Modules

Defined in:

file.cr

Instance Method Summary

Instance methods inherited from class Reference

==(other : NASON::Any) ==

Instance methods inherited from class Object

===(other : NASON::Any) ===, nil_or_null? nil_or_null?, not_null! not_null!, null? null?, to_nason(io : IO) : Nil
to_nason : String
to_nason
, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil
to_pretty_json

Class methods inherited from class Object

from_nason(string_or_io, root : String)
from_nason(string_or_io)
from_nason

Instance Method Detail

def to_json(json : NASON::Builder) #

[View source]