可选的第二个参数被称为模式字符串,它告诉如何打开文件(用于读,写或其它)。模式字符串不做任何事情,它只是个许可。缺省值"r"用于读。这儿是个例子:
file1 = File.new("one")
# Open for reading
file2 = File.new("two", "w")
# Open for writing
new的另一种形式接受三个参数。在这种情况,第二个参数指出文件的原始许可(通常是八进制常量),第三个参数是一组Ored标志。标志是个常量如File:CREAT(当打开时,如果文件不存在则创建它)和File:RDONLY(以只读方式打开文件)。这种形式很少使用。这儿是个例子:
file = File.new("three", 0755, File::CREAT|File::WRONLY)
出于对操作系统或运行时环境的礼貌,总是要关闭你打开的文件。在用于写而打开文件情况下,更应如此才能避免丢失数据。不出意外,close方法用于做到点:
out = File.new("captains.log", "w")
# 必须的步骤...
out.close
这儿是open方法,它简单形式内,它不过是new的同义字,像这样:
trans = File.open("transactions","w")
但是,open可以接受块;这个形式更有趣。当指定块时,打开的文件会被做为参数传递给块。在块的作用域内文件一直保持打开状态,在退出块时自动关闭。这儿是个例子:
File.open("somefile","w") do |file|
file.puts "Line 1"
file.puts "Line 2"
file.puts "Third and final line"
end
# The file is now closed
当我们结束对文件的操作时,很明显这是关闭文件的优雅方式。此外,管理文件的代码在视觉上是个单元。
file = File.new(“testfile”, “r”)# … process the filefile.closetestfile是想要操作的文件名,”r”说明了文件的操作模式为读取。可以使用”w”表示写入,”rw”表示读写。最后要记得关闭打开的文件,确保所有被缓冲的数据被写入文件,所有相关的资源被释放。也可以使用File.open来打开文件,open和new的不同是open可以使用其后的代码块而new方法则返回一个File类的实例。File.open(“testfile”, “r”) do |file|# … process the fileendopen操作的另一个优点是处理了异常,如果处理一个文件发生错误抛出了异常的话,那么open操作会自动关闭这个文件,下面是open操作的大致实现:class Filedef File.open(*args)result = f = File.new(*args)if block_given?beginresult = yield fensuref.closeendendreturn resultendend对于文件的路径,Ruby会在不同的操作系统间作转换。例如,在Windows下,/ruby/sample/test.rb会被转化为\ruby\sample\test.rb。当你使用字符串表示一个Windows下的文件时,请记住使用反斜线先转义:一、新建文件
f=File.new(File.join("C:","Test.txt"), "w+")
f.puts("I am Jack")
f.puts("Hello World")
文件模式
"r" :Read-only. Starts at beginning of file (default mode).
"r+" :Read-write. Starts at beginning of file.
"w" :Write-only. Truncates existing file to zero length or creates a new file for writing.
"w+" :Read-write. Truncates existing file to zero length or creates a new file for reading and writing.
"a" :Write-only. Starts at end of file if file existsotherwise, creates a new file for writing.
"a+" :Read-write. Starts at end of file if file existsotherwise, creates a new file for reading and writing.
"b" :(DOS/Windows only.) Binary file mode. May appear with any of the key letters listed above
二、读取文件
file=File.open(File.join("C:","Test.txt"),"r")
file.each { |line| print "#{file.lineno}.", line }
file.close
三、新建、删除、重命名文件
File.new( "books.txt", "w" )
File.rename( "books.txt", "chaps.txt" )
File.delete( "chaps.txt" )
四、目录操作
1 创建目录
Dir.mkdir("c:/testdir")
04 #删除目录
05 Dir.rmdir("c:/testdir")
07 #查询目录里的文件
08 p Dir.entries(File.join("C:","Ruby")).join(' ')
10 #遍历目录
11 Dir.entries(File.join("C:","Ruby")).each {
|e| puts e
}
1、ARGV and ARGF
ARGV
ARGV <<"cnblogslink.txt"
#The gets method is a Kernel method that gets lines from ARGV
print while gets
p ARGV.class
ARGF
while line = ARGF.gets
print line
end
2、文件信息查询
#文件是否存在
p File::exists?( "cnblogslink.txt" ) # =>true
#是否是文件
p File.file?( "cnblogslink.txt" ) # =>true
#是否是目录
p File::directory?( "c:/ruby" ) # =>true
p File::directory?( "cnblogslink.txt" ) # =>false
#文件权限
p File.readable?( "cnblogslink.txt" ) # =>true
p File.writable?( "cnblogslink.txt" ) # =>true
p File.executable?( "cnblogslink.txt" ) # =>false
#是否是零长度
p File.zero?( "cnblogslink.txt" ) # =>false
#文件大小 bytes
p File.size?( "cnblogslink.txt" ) # =>74
p File.size( "cnblogslink.txt" ) # =>74
#文件或文件夹
p File::ftype( "cnblogslink.txt" ) # =>"file"
#文件创建、修改、最后一次存取时间
p File::ctime( "cnblogslink.txt" ) # =>Sat Sep 19 08:05:07 +0800 2009
p File::mtime( "cnblogslink.txt" ) # =>Sat Sep 19 08:06:34 +0800 2009
p File::atime( "cnblogslink.txt" ) # =>Sat Sep 19 08:05:07 +0800 2009
3、查找文件
puts "查找目录下所有文件及文件夹"
Dir["c:/ruby/*"].each {|x|
puts x
}
puts "条件查询"
Dir.foreach('c:/ruby') {
|x| puts x if x != "." &&x != ".."
}
puts "查找某一类型文件"
Dir["*.rb"].each {|x|
puts x
}
puts "Open 查询"
Dir.open('c:/ruby') { |d| d.grep /l/ }.each{|x| puts x}
puts "---------------------------"
puts "正则表达式查询"
Dir["c:/ruby/ruby/[rs]*"].each{|x| puts x}
puts "------------------------"
Dir["c:/ruby/[^s]*"].each{|x| puts x}
puts "------------------------"
Dir["c:/ruby/{ruby,li}*"].each{|x| puts x}
puts "------------------------"
Dir["c:/ruby/?b*"].each{|x| puts x}
puts "查找目录及子目录的文件"
require 'find'
Find.find('./') { |path| puts path }
3、查询目录及子目录文件
require "find"
Find.find("/etc/passwd", "/var/spool/lp1", ".") do |f|
Find.prune if f == "."
puts f
end
原型:ref.find( [ aName ]* ) {| aFileName | block }
prune:Skips the current file or directory, restarting the loop with the next entry. If the current file is a directory, that directory will not be recursively entered. Meaningful only within the block associated with Find::find.
4、文件比较 复制等
require 'ftools'
File.copy 'testfile', 'testfile1' » true
File.compare 'testfile', 'testfile1' » true