创建文件
aFile = File.new("filename", "mode")
# ... 处理文件
aFile.puts "test" #puts输出又换行功能,想当予后面加了\n
aFile.close
打开文件追加内容
File.open("filename", "a+") do |f|
# ... process the file
f.puts "lyp"
f.puts "123"
end
得到文件内容
aFile = File.new("input.txt", "r")
if aFile
content = aFile.sysread(20)
puts content
else
puts "Unable to open file!"
end
每行作为一个元素放数组里,如下:
arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]
循环行
IO.foreach("input.txt") do |line|
puts line
end
重命名和删除文件
您可以通过 rename 和 delete 方法重命名和删除文件。
# 重命名文件 test1.txt 为 test2.txt
File.rename( "test1.txt", "test2.txt" )
# 删除文件 test2.txt
File.delete("text2.txt")
判断文件或者目录是否存在
# 文件是否存在返回 true 或false
File.file?( "text.txt" )
# 目录是否存在返回 true 或false
File::directory?( "/usr/local/bin" ) # => true
检查文件是否可读、可写、可执行
File.readable?( "test.txt" ) # => true 可读
File.writable?( "test.txt" ) # => true 可写
File.executable?( "test.txt" ) # => false 不可可执行
检查文件是否大小为零
File.zero?("test.txt") # => true
获取文件大小
File.size?( "text.txt" ) # => 1002
获取文件被创建、修改或最后访问的时间
File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008
File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008
File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008
创建删除目录
Dir.mkdir("mynewdir")
Dir.mkdir( "mynewdir", 755 )
Dir.delete("testdir") #删除目录
您也可以通过 mkdir 在新目录(不是已存在的目录)上设置权限:
注意:掩码 755 设置所有者(owner)、所属组(group)、每个人(world [anyone])的权限为 rwxr-xr-x,其中 r = read 读取,w = write 写入,x = execute 执行。