class

File

Inherits Crystal::System::File < IO::FileDescriptor < IO::Buffered < Crystal::System::FileDescriptor < IO < Reference < Object

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:12Z
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

Constructors

new(path : Pathname, mode = "r", perm = DEFAULT_CREATE_MODE, encoding = nil, invalid = nil)
Source

Class methods

basename(path : Pathname, suffix)
Source
basename(path : Pathname)
Source
delete(path : Pathname)
Source
directory?(path : Pathname)
Source
dirname(path : Pathname)
Source
each_line(path : Pathname, &)
Source
executable?(path : Pathname)
Source
exists?(path : Pathname)
Source
expand_path(path : Pathname, dir = nil)
Source
extname(path : Pathname)
Source
file?(path : Pathname)
Source
lstat(path : Pathname)
Source
open(path : Pathname, mode = "r", perm = DEFAULT_CREATE_MODE, encoding = nil, invalid = nil)
Source
open(path : Pathname, mode = "r", perm = DEFAULT_CREATE_MODE, encoding = nil, invalid = nil, &)
Source
read(path : Pathname, encoding = nil, invalid = nil)
Source
read_lines(path : Pathname, encoding = nil, invalid = nil)
Source
readable?(path : Pathname)
Source
real_path(path : Pathname)
Source
rename(old_path : Pathname, new_path : Pathname)
Source
rename(old_path : Pathname, new_path)
Source
rename(old_path, new_path : Pathname)
Source
size(path : Pathname)
Source
stat(path : Pathname)
Source
writable?(path : Pathname)
Source
write(path : Pathname, content, perm = DEFAULT_CREATE_MODE, encoding = nil, invalid = nil)
Source