ruby 文件操作 转! 1 检测文件是否存在及其大小 FileTest 的 exist?方法可以检测一个文件是否存在: 代码: 代码: flag = FileTest::exist?("LochNessMonster") flag = FileTest::exists?("UFO") # exists? is a synonym for exist?
如果我们想要知道文件是否有内容,可以使用 File::Stat 的 zero? 方法: 代码: 代码: flag = File.new("somefile").stat.zero?
这个将会返回 true,这是因为在 ruby 中 0 也是 true,nil 才是 false. 所以我们可以使用 size?方法: 代码: 代码: if File.new("myfile").stat.size? puts "The file has contents." else puts "The file is empty." end
FileTest 模块里面也有 zero? 和 size?方法: 代码: 代码: flag1 = FileTest::zero?("file1") flag2 = FileTest::size?("file2")
这里还有一个 size 方法: 代码: 代码: size1 = File.size("file1") size2 = File.stat("file2").size
2 检测特殊文件属性 这边要注意,File 类 mix 了 FIleTest 模块,并且 FileTest 模块和 File::Stat 模块功能上也有很多重复. unix/
linux 有面向字符和面向块的设备。 FileTest 的方法 blockdev?和 chardev? 可以进行测试: 代码: 代码: flag1 = FileTest::chardev?("/dev/hdisk0") # false flag2 = FileTest::blockdev?("/dev/hdisk0") # true
有时我们想要知道一个流是否联系到了终端,这时我们可以使用 IO 类的 tty?方 法: 代码: 代码: flag1 = STDIN.tty? # true flag2 = File.new("diskfile").isatty # false
一个流可以是一个管道,或者一个 socket: 代码: 代码: flag1 = FileTest::pipe?(myfile) flag2 = FileTest::socket?(myfile)
要区分目录和普通文件我们这样使用: 代码: 代码: file1 = File.new("/tmp") file2 = File.new("/tmp/myfile") test1 = file1.directory? # test2 = file1.file? # test3 = file2.directory? # test4 = file2.file? #
true false false true
File 还有一个类方法 ftype,他将返回流的类型.他也在 File::Stat 里面,只不 过是实例方法.它的返回值可能是下面的字符 串(file、 directory、 blockSpecial、 characterSpecial、 fifo、 link 或 socket). 代码: 代码:
this_kind = File.ftype("/dev/hdisk0") that_kind = File.new("/tmp").stat.ftype
# "blockSpecial" # "directory"
要测试一个文件是否为另一个文件的链接, 可以使用 FileTest 的 symlink?方法, 要计算链接数量,可以使用 nlink 方法: 代码: 代码: File.symlink("yourfile","myfile") # Make a link is_sym = FileTest::symlink?("myfile") # true hard_count = File.new("myfile").stat.nlink # 0
3 使用管道 ruby 中使用 IO.popen 打开管道: 代码: 代码: check = IO.popen("spell","r+") check.puts("'T was brillig, and the slithy toves") check.puts("Did gyre and gimble in the wabe.") check.close_write list = check.readlines list.collect! { |x| x.chomp } # list is now %w[brillig gimble gyre slithy toves wabe]
要注意 必须调用 close_write,如果没有调用它,读取管道的时候,就不能到达 文件的末尾. 下面是一个 block 的形式: 代
码: 代码: File.popen("/usr/games/fortune") do |pipe| quote = pipe.gets puts quote # On a clean disk, you can seek forever. - Thomas Steel end
如果指定了一个字符串"-",那么一个新的 ruby 实例将被创建.如果指定了一个 block,那么这个 block 将会作为两个独立
的进程运行。子进程得到 nil,父进程得到一个 IO 对象: 代码: 代码: IO.popen("-") do |mypipe| if mypipe puts "I'm the parent: pid = #{Process.pid}" listen = mypipe.gets puts listen else puts "I'm the child: pid = #{Process.pid}" end end
# Prints: # I'm the parent: pid = 10580 # I'm the child: pid = 10582
pipe 方法也返回互相连接的一对管道: 代码: 代码: pipe = IO.pipe reader = pipe[0] writer = pipe[1] str = nil thread1 = Thread.new(read