1、文件读写实例
TEST_FILE_NAME = "testfile.txt"
#create a new file and add some lines
File.open(TEST_FILE_NAME,"w+") do |file|
(1..10).each do |i|
file.puts "#{i}"
end
end
#append some lines
File.open(TEST_FILE_NAME,"a+") do |file|
(1..2).each do |i|
file.puts "add #{i}"
end
end
#show file
File.open(TEST_FILE_NAME,"r") do |file|
file.each_line do |line|
puts "#{file.lineno} : #{line}"
end
end
#rename
File.rename(TEST_FILE_NAME,"new_name.txt");
#delete
File.delete("new_name.txt");
2、获取文件大小,时间属性等操作。
TEST_FILE_NAME = "testfile.txt"
#create a new file and add some lines
File.open(TEST_FILE_NAME,"w+") do |file|
(1..10).each do |i|
file.puts "#{i}"
end
end
size = File.size(TEST_FILE_NAME)
puts "#{TEST_FILE_NAME}'s size is #{size}"
#get file's stat
stat = File.open(TEST_FILE_NAME).stat
puts "create time is #{stat.ctime}"
puts "modify time is #{stat.mtime}"
puts "access time is #{stat.atime}"
3、目录操作,创建、删除目录
puts "current dir is #{Dir.pwd}"
#create dir
Dir.mkdir("new_dir")
#list all file and dir in current path
Dir.foreach(Dir.pwd) do |dir|
puts dir
end
#delete dir
Dir.delete("new_dir");
4、列出当前目录下 的所有文件和文件夹
puts "current dir is #{Dir.pwd}"
#列出当前目录下的所有目录和子目录中的文件
Dir.glob('**/**') do |file|
puts file
end
#find方法列出的是每个文件和文件夹的绝对路径
puts "find method"
require "find"
Find.find(Dir.pwd) do |file|
puts file
end