文件处理选择项的意思

r #reading
r+ #opening a file for updating, both reading and writing
a #appending to a file
a+ #open a file for reading and appending
w #just writing
w+ #reading & writing

File的open和new作用相同

#说明
如果没有接受块,那么open和new方法的作用是一致的,如果open带有块,那么文件会自动会close, new不会带块参数

#使用File.open创建文件,并在文件中写入内容
File.open("./demo.txt", "w+"){|f| f.write("hello world")}

#使用File.new创建文件
file_to_save = File.new("./demo.txt", "w+")
file_to_save.puts("hello world")
file_to_save.close

File的read功能

#read功能
teams = File.read("demo.txt")
p teams

File的delete功能

#一般形式
File.delete("./demo.txt")

#处理文件不存在形式
begin
  File.delete("./demo.txt")
rescue StandardError => e
  p "this is a error #{e}"
end

File的append功能

10.times do
  sleep 1
  puts "record saved..."
  File.open("./demo.txt", "a"){ |file| file.puts "server startd at: #{Time.now}"}
end

results matching ""

    No results matching ""