当前位置: 首页 > 工具软件 > Ruby TTY > 使用案例 >

Ruby 文件目录操作(实例讲解更易懂)

孔君浩
2023-12-01

IO 操作

$stdout

[4] pry(main)> $stdout.print "Output to $stdout.\n"
Output to $stdout.
=> nil

$stderr

[5] pry(main)> $stderr.print "Output to $stderr.\n"
Output to $stderr.
=> nil

$stdin

# tty.rb
if $stdin.tty?
  print "Stdin is a TTY.\n"
else  
  print "Stdin is not a TTY.\n"
end 

[root@master ruby_learning]# ruby tty.rb
Stdin is a TTY.

[root@master ruby_learning]# echo | ruby tty.rb
Stdin is not a TTY.

io.gets

[root@master ruby_learning]# ls
hello.rb  test.rb  test.txt

[1] pry(main)> File.open("test.txt") do |io|
[1] pry(main)*   while line = io.gets
[1] pry(main)*     puts line
[1] pry(main)*   end  
[1] pry(main)* end  
hello
world
=> nil

[8] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[9] pry(main)> io.class
=> File
[10] pry(main)> io.gets
=> "hello\n"
[11] pry(main)> io.gets
=> "world\n"
[12] pry(main)> io.gets
=> nil

io.close?

[3] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[5] pry(main)> io.closed?
=> false
[6] pry(main)> io.close
=> nil
[7] pry(main)> io.closed?
=> true

io.each_line

[15] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[16] pry(main)> io.each_line do |line|
[16] pry(main)*   line.chomp!
[16] pry(main)*   puts line
[16] pry(main)* end  
hello
world
=> #<File:test.txt>

 io.readlines

[20] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[21] pry(main)> ary = io.readlines
=> ["hello\n", "world\n"]
[22] pry(main)> ary.each do |line|
[22] pry(main)*   line.chomp!
[22] pry(main)*   puts line
[22] pry(main)* end  
hello
world
=> ["hello", "world"]

io.lineno

[25] pry(main)> $stdin.each_line do|line|
[25] pry(main)*   printf("%3d %s", $stdin.lineno, line)
[25] pry(main)* end  
hello
  1 hello
world
  2 world

io.each_char

[26] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[27] pry(main)> io.each_char do |ch|
[27] pry(main)*   puts ch
[27] pry(main)* end  
h
e
l
l
o

w
o
r
l
d

io.each_byte

[30] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[32] pry(main)> io.each_byte do |byte|
[32] pry(main)*   puts byte
[32] pry(main)* end  
104
101
108
108
111
10
119
111
114
108
100
10

io.getc

[33] pry(main)> io = File.open("test.txt")
=> #<File:test.txt>
[34] pry(main)> while ch = io.getc
[34] pry(main)*   puts ch
[34] pry(main)* end  
h
e
l
l
o

w
o
r
l
d

=> nil

io.read

[41] pry(main)> File.open("test.txt") do |io|
[41] pry(main)*   puts io.read(5)
[41] pry(main)*   puts io.read
[41] pry(main)* end  
hello

world
=> nil

io.puts

[42] pry(main)> $stdout.puts "foo", "bar", "baz"
foo
bar
baz
=> ni

io.putc

[43] pry(main)> $stdout.putc 82
R=> 82
[44] pry(main)> $stdout.putc "Ruby"
R=> "Ruby"
[45] pry(main)> $stdout.putc "\n"

=> "\n"
[46] pry(main)> 

io.write

[55] pry(main)> File.open("foo.txt", "w") do |io|
[55] pry(main)*   io.write "Hello, world.\n"
[55] pry(main)* end  
=> 14

[root@master ruby_learning]# cat foo.txt
Hello, world.

# 往文件追加新行内容
[55] pry(main)> File.open("foo.txt", "a") do |io|
[55] pry(main)*   io.puts "Hello, world."
[55] pry(main)* end  
=> nil

[root@master ruby_learning]# cat foo.txt
Hello, world.
Hello, world.

io.pos

[50] pry(main)> File.open("test.txt") do |io|
[50] pry(main)*   puts io.read 5
[50] pry(main)*   puts io.pos
[50] pry(main)*   io.pos = 0
[50] pry(main)*   puts io.gets
[50] pry(main)* end  
hello
5
hello
=> nil

io.rewind

[51] pry(main)> File.open("test.txt") do |io|
[51] pry(main)*   puts io.gets
[51] pry(main)*   io.rewind
[51] pry(main)*   puts io.gets
[51] pry(main)* end  
hello
hello
=> nil

io.popen

[59] pry(main)> io = IO.popen("ls")
=> #<IO:fd 16>
[60] pry(main)> io.each_line do |line|
[60] pry(main)*   puts line
[60] pry(main)* end  
foo.txt
hello.rb
test.rb
test.txt
=> #<IO:fd 16>

[65] pry(main)> io.to_a
=> ["foo.txt\n", "hello.rb\n", "test.rb\n", "test.txt\n"]
[66] pry(main)> `ls`
=> "foo.txt\nhello.rb\ntest.rb\ntest.txt\n"

io.open("| ...")

[70] pry(main)> open("|ls").each do |line|
[70] pry(main)*   puts line
[70] pry(main)* end  
foo.txt
hello.rb
test.rb
test.txt
=> #<IO:fd 20>


[71] pry(main)> open("|ls").to_a
=> ["foo.txt\n", "hello.rb\n", "test.rb\n", "test.txt\n"]

open-uri

[74] pry(main)> require 'open-uri'
=> true
[75] pry(main)> open("http://www.ruby-lang.org") do |io|
[75] pry(main)*   puts io.read
[75] pry(main)* end  
(pry):120: warning: calling URI.open via Kernel#open is deprecated, call URI.open directly or use URI#open
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ruby Programming Language</title>
    <script type="text/javascript">
      var languages = {
        "de":    "de",
        "es":    "es",
        "id":    "id",
        "ja":    "ja",
        "ko":    "ko",
        "pt":    "pt",
        "tr":    "tr",
        "zh-CN": "zh_cn",
        "zh-TW": "zh_tw"
      };

      var code = window.navigator.language || window.navigator.userLanguage || "en";
      if (code.substr(0,2) !== "zh") { code = code.substr(0,2); }

      var language = languages[code];
      if (!language) { language = "en"; }

      document.location = "/" + language + "/";
    </script>
    <noscript>
      <meta http-equiv="refresh" content="0; url=/en/">
    </noscript>
  </head>
  <body>
    <p><a href="/en/">Click here</a> to be redirected.</p>
  </body>
</html>
=> nil

stringio

[79] pry(main)> require 'stringio'
[80] pry(main)> io = StringIO.new
=> #<StringIO:0x0000558ba1bc7898>
[81] pry(main)> io.puts 'A'
=> nil
[82] pry(main)> io.puts 'B'
=> nil
[83] pry(main)> io.puts 'C'
=> nil
[84] pry(main)> io.rewind
=> 0
[85] pry(main)> io.read
=> "A\nB\nC\n"

File 操作

File::atime( path)

返回 path 的最后访问时间(access time)。

# Ruby
[33] pry(main)> File::atime("hello.rb")
=> 2020-08-15 21:22:51 +0800

# 执行 cat hello.rb 后
# [root@master workspace]# cat hello.rb

[34] pry(main)> File::atime("hello.rb")
=> 2020-08-15 21:30:18 +0800

File::ctime( path)

返回 path 的最后状态时间(change time)。

# Ruby
[28] pry(main)> File::ctime("hello.rb")
=> 2020-08-15 21:22:51 +0800
[30] pry(main)> File::mtime("hello.rb")
=> 2020-08-15 21:22:51 +0800

# 对 hello.rb 权限修改(没修改文件内容)
# [root@master workspace]# chmod 644 hello.rb

[29] pry(main)> File::ctime("hello.rb")
=> 2020-08-15 21:26:40 +0800
[30] pry(main)> File::mtime("hello.rb")
=> 2020-08-15 21:22:51 +0800

File::mtime( path)

返回 path 的最后修改时间(modify time)。

# Ruby
[35] pry(main)> File::ctime("hello.rb")
=> 2020-08-15 21:28:18 +0800
[36] pry(main)> File::mtime("hello.rb")
=> 2020-08-15 21:22:51 +0800

# 执行 vim 修改并保存后
# [root@master workspace]# vim hello.rb

[37] pry(main)> File::ctime("hello.rb")
=> 2020-08-15 21:34:03 +0800
[38] pry(main)> File::mtime("hello.rb")
=> 2020-08-15 21:34:03 +0800

File::basename( path[, suffix])

返回 path 末尾的文件名。如果指定了 suffix(后缀),则它会从文件名末尾被删除。

# Ruby
[4] pry(main)> File::basename("/root/workspace/hello.rb")
=> "hello.rb"
[6] pry(main)> File::basename("/root/workspace/hello.rb.bak", ".bak")
=> "hello.rb"

File::blockdev?( path)

如果 path 是一个块设备,则返回 true。

# Ruby
[7] pry(main)> File::blockdev?("hello.rb")
=> false
[12] pry(main)> File::blockdev?("/dev/dm-0")
=> true

[root@master dev]# ll
...
crw-------. 1 root root     10,  62 Aug 15 16:27 crash
drwxr-xr-x. 5 root root         100 Aug 15 16:27 disk
brw-rw----. 1 root disk    253,   0 Aug 15 16:27 dm-0
brw-rw----. 1 root disk    253,   1 Aug 15 16:27 dm-1
crw-rw----. 1 root audio    14,   9 Aug 15 16:27 dmmidi
...

File::chardev?( path)

如果 path 是一个字符设备,则返回 true。

# Ruby
[14] pry(main)> File::chardev?("hello.rb")
=> false
[15] pry(main)> File::chardev?("/dev/snapshot")
=> true

[root@master dev]# ll
crw-rw----. 1 root cdrom    21,   1 Aug 15 16:27 sg1
drwxrwxrwt. 2 root root          40 Aug 15 16:27 shm
crw-------. 1 root root     10, 231 Aug 15 16:27 snapshot
drwxr-xr-x. 3 root root         200 Aug 15 16:27 snd

# 字符设备不可像普通文件那样用 cat, vim 命令查看哟
[root@master dev]# cat snapshot
cat: snapshot: No data available
[root@master dev]# vim snapshot                                                                                                             
~                                                                                                                                                                                                                                    
~                                                                                                                    
"full" is not a file 

File::chmod( mode, path...)

改变指定文件的权限模式。

# Ruby
[root@master workspace]# ll
total 28
drwxr-xr-x. 2 root root   6 Aug 12 20:45 crystal_learning
-rwxrwxrwx. 1 root root  68 Jul 30 22:46 hello
-rw-r--r--. 1 root root  68 Aug 15 20:46 hello.rb

[17] pry(main)> File::chmod(777, "hello.rb")
=> 1

[root@master workspace]# ll
total 28
drwxr-xr-x. 2 root root   6 Aug 12 20:45 crystal_learning
-rwxrwxrwx. 1 root root  68 Jul 30 22:46 hello
-r----x--t. 1 root root  68 Aug 15 20:46 hello.rb

File::chown( owner, group, path...)

改变指定文件的所有者和所属组。

# Ruby
# 查看 hello.rb 文件当前所属组(现在是 root 用户的)
[root@master workspace]# ll
total 28
drwxr-xr-x. 2 root root   6 Aug 12 20:45 crystal_learning
-rwxrwxrwx. 1 root root  68 Jul 30 22:46 hello
-rw-r--r--. 1 root root  68 Aug 15 21:12 hello.rb

# 查看 looking 用户的ID、组ID
[root@master workspace]# cat /etc/passwd
...
ntp:x:38:38::/etc/ntp:/sbin/nologin
looking:x:1001:1001::/home/looking:/bin/bash

# 把 hello.rb 文件的所有者和所属组给 looking 用户
[23] pry(main)> File::chown(1001, 1001, "hello.rb")
=> 1
# 现在 hello.rb 文件是 looking 用户的了

[root@master workspace]# ll
total 28
drwxr-xr-x. 2 root    root      6 Aug 12 20:45 crystal_learning
-rwxrwxrwx. 1 root    root     68 Jul 30 22:46 hello
-rw-r--r--. 1 looking looking  68 Aug 15 21:12 hello.rb

File::delete( path...) [or] File::unlink( path...)

删除指定的文件,文件不存在会报错。

# Ruby
[39] pry(main)> File::delete("hello.rb")
=> 1
[40] pry(main)> File::delete("hello.rb")
Errno::ENOENT: No such file or directory - helo.rb
from (pry):39:in "delete"

# 重新创建 hello.rb 文件
# [root@master workspace]# cat hello.rb.bak > hello.rb

[41] pry(main)> File::unlink("hello.rb")
=> 1
[42] pry(main)> File::unlink("hello.rb")
Errno::ENOENT: No such file or directory - hello.rb
from (pry):41:in "unlink"

File::directory?( path)

如果 path 是一个目录,则返回 true。

# Ruby
[43] pry(main)> File::directory?("hello.rb")
=> false
[46] pry(main)> File::directory?("/root/workspace")
=> true

File::dirname( path)

返回 path 的目录部分,不包括最后的文件名。

# Ruby
[49] pry(main)> File::dirname("hello.rb")
=> "."
[50] pry(main)> File::realpath("hello.rb")
=> "/root/workspace/hello.rb"
[51] pry(main)> File::dirname(File::realpath("hello.rb"))
=> "/root/workspace"

File::extname( path)

返回 path 的扩展名部分。

[1] pry(main)> File::extname "hello.txt"
=> ".txt"
[2] pry(main)> File::extname "hello"
=> ""
[3] pry(main)> File::extname "/root/hello.rb"
=> ".rb"

File::realpath( file)

返回文件的绝对路径。

# Ruby
[52] pry(main)> File::realpath("hello.rb")
=> "/root/workspace/hello.rb"

File::executable?( path)

如果 path 是可执行的,则返回 true。

# Ruby
[56] pry(main)> File::executable?("hello.rb")
=> false
[57] pry(main)> File::executable?("hello")
=> true

File::executable_real?( path)

如果 path 通过真正的用户权限是可执行的,则返回 true。

# Ruby
[58] pry(main)> File::executable_real?("hello.rb")
=> false
[59] pry(main)> File::executable_real?("hello")
=> true

File::exist?( path)

如果 path 存在,则返回 true。

# Ruby
[60] pry(main)> File::exist?("hello.rb")
=> true
[61] pry(main)> File::exist?("world.rb")
=> false

File::expand_path( path[, dir])

有点类似于获取文件的绝对路径(即使文件不存在也会返回结果)

# Ruby
[62] pry(main)> File::expand_path("hello.rb")
=> "/root/workspace/hello.rb"

# 目录下 world.rb 文件不存在哟 
[63] pry(main)> File::expand_path("world.rb")
=> "/root/workspace/world.rb"

File::file?( path)

如果 path 是一个普通文件,则返回 true。文件不存在的话也会返回 false。

# Ruby
[65] pry(main)> File::file?("hello.rb")
=> true
[67] pry(main)> File::file?("/dev/full")
=> false

File::ftype( path)

返回下列其中一个字符串,表示文件类型:

  • file - 普通文件
  • directory - 目录
  • characterSpecial - 字符特殊文件
  • blockSpecial - 块特殊文件
  • fifo - 命名管道(FIFO)
  • link - 符号链接
  • socket - Socket
  • unknown - 未知的文件类型
# Ruby
[70] pry(main)> File::ftype("hello.rb")
=> "file"
[71] pry(main)> File::ftype("ruby_learning")
=> "directory"

File::grpowned?( path)

如果 path 由用户的所属组所有,则返回 true。

# Ruby
[72] pry(main)> File::grpowned?("hello.rb")
=> true

File::join( item...)

返回一个字符串,由指定的项连接在一起,并使用 File::Separator 进行分隔。

# Ruby
[76] pry(main)> File::join("root", "workspace")
=> "root/workspace"
[77] pry(main)> File::join("", "root", "workspace")
=> "/root/workspace"

File::link( old, new)

创建一个到文件 old 的硬链接。

# Ruby
[78] pry(main)> File::link("hello.rb", "hello.rb.link")
=> 0

[root@master workspace]# ll
total 32
drwxr-xr-x. 2 root    root      6 Aug 12 20:45 crystal_learning
-rwxrwxrwx. 1 root    root     68 Jul 30 22:46 hello
-rw-r--r--. 2 looking looking  68 Aug 15 21:42 hello.rb
-rw-r--r--. 1 root    root     68 Aug 15 20:52 hello.rb.bak
-rw-r--r--. 2 looking looking  68 Aug 15 21:42 hello.rb.link

File::lstat( path)

与 stat 相同,但是它返回自身符号链接上的信息,而不是所指向的文件。

# Ruby
[80] pry(main)> File::lstat("hello.rb")
=> #<File::Stat
 dev=0xfd00,
 ino=35406947,
 mode=0100644 (file rw-r--r--),
 nlink=1,
 uid=1001 (looking),
 gid=1001 (looking),
 rdev=0x0 (0, 0),
 size=87,
 blksize=4096,
 blocks=8,
 atime=2020-08-15 22:09:01 +0800 (1597500541),
 mtime=2020-08-15 22:08:58 +0800 (1597500538),
 ctime=2020-08-15 22:10:22 +0800 (1597500622)>

File::new( path[, mode="r"])

打开文件。

# Ruby
[81] pry(main)> File::new("hello.rb")
=> #<File:hello.rb>
[82] pry(main)> File::new("hello.rb").readlines()
=> ["#!/usr/bin/env ruby\n",
 "ARGV.each do |item|\n",
 "  puts \"Hello, \#{item}\"\n",
 "end\n",
 "puts \"hello world\"\n"]

File::open(path[, mode="r"]) {|f| ...}

打开文件。传递新文件作为参数来执行块。当块退出时,文件会自动关闭。

# Ruby
[87] pry(main)> File::open("hello.rb") do |f|
[87] pry(main)*   files = f.readlines
[87] pry(main)*   files.each do |line|
[87] pry(main)*     puts line
[87] pry(main)*   end  
[87] pry(main)* end  
#!/usr/bin/env ruby
ARGV.each do |item|
  puts "Hello, #{item}"
end
puts "hello world"
=> ["#!/usr/bin/env ruby\n",
 "ARGV.each do |item|\n",
 "  puts \"Hello, \#{item}\"\n",
 "end\n",
 "puts \"hello world\"\n"]

File::foreach(path) 

遍历读取文件每一行

irb(main):002:0> File::foreach("/root/test.txt") do |line|
irb(main):003:1*     puts line
irb(main):004:1> end
hello 
world
forwarder df brokendf
nice
to
meet
you
=> nil

File::owned?(path)

如果 path 由有效的用户所有,则返回 true。

# Ruby
# -rw-r--r--. 1 looking looking  87 Aug 15 22:08 hello.rb
# 我把 hello.rb 的 ownship 给 looking 用户了,不知道这儿怎么就返回 false 了?
[89] pry(main)> File::owned?("hello.rb")
=> false
[90] pry(main)> File::owned?("hello")
=> true

File::pipe?( path)

如果 path 是一个管道,则返回 true。

# Ruby
[92] pry(main)> File::pipe?("hello.rb")
=> false
[93] pry(main)> File::pipe?("test.pipe")
=> true

File::read(path)

读取文件内容

[11] pry(main)> File::read('/root/test.txt')                                                                                     
=> "hello world\nnice to meet you"

File::readlines(path) 

[1] pry(main)> File.readlines("/root/test.txt")
=> ["hello \n", "world\n", "forwarder df brokendf\n", "nice\n", "to\n", "meet\n", "you\n"]

File::readable?( path)

如果 path 是可读的,则返回 true。

# Ruby
[94] pry(main)> File::readable?("hello.rb")
=> true

File::readable_real?( path)

如果 path 通过真正的用户权限是可读的,则返回 true。

# Ruby
[96] pry(main)> File::readable_real?("hello.rb")
=> true

File::readlink( path)

返回 path(符号链接) 所指向的文件。

# Ruby
[101] pry(main)> File::readlink("softlink_hello.rb")
=> "hello.rb"

File::rename( old, new)

改变文件名 old 为 new。

# Ruby
[102] pry(main)> File.rename("hello.rb", "world.rb")
=> 0

File::setgid?( path)

如果设置了 path 的 set-group-id 权限位,则返回 true。

# Ruby
[104] pry(main)> File::setgid?("hello.rb")
=> false

File::setuid?( path)

如果设置了 path 的 set-user-id 权限位,则返回 true。

# Ruby
[105] pry(main)> File::setuid?("hello.rb")
=> false

File::size( path)

返回 path 的文件大小,如果文件不存在则报错。

# Ruby
[106] pry(main)> File::size("hello.rb")
=> 87
[107] pry(main)> File::size("hel.rb")
Errno::ENOENT: No such file or directory - hel.rb
from (pry):119:in `size'

File::size?( path)

返回 path 的文件大小,如果为 0 或者文件不存在则返回 nil。

# Ruby
[108] pry(main)> File::size?("hello.rb")
=> 87
[109] pry(main)> File::size?("hel.rb")
=> nil

File::socket?( path)

如果 path 是一个 socket,则返回 true。

# Ruby
[110] pry(main)> File::socket?("hello.rb")
=> false

File::split( path)

返回一个数组,包含 path 的内容,path 被分成 File::dirname(path) 和 File::basename(path)。

# Ruby
[112] pry(main)> File::split("/root/workspace/hello.rb")
=> ["/root/workspace", "hello.rb"]

File::stat( path)

返回 path 上带有信息的 File::Stat 对象。

# Ruby
[113] pry(main)> File::stat("hello.rb")
=> #<File::Stat
 dev=0xfd00,
 ino=35406947,
 mode=0100644 (file rw-r--r--),
 nlink=1,
 uid=1001 (looking),
 gid=1001 (looking),
 rdev=0x0 (0, 0),
 size=87,
 blksize=4096,
 blocks=8,
 atime=2020-08-15 22:12:21 +0800 (1597500741),
 mtime=2020-08-15 22:08:58 +0800 (1597500538),
 ctime=2020-08-15 22:35:31 +0800 (1597502131)>

File::sticky?( path)

如果设置了 path 的 sticky 位,则返回 true。

# Ruby
[114] pry(main)> File::sticky?("hello.rb")
=> false

File::symlink( old, new)

创建一个指向文件 old 的符号链接。

# Ruby
[115] pry(main)> File::symlink("hello.rb", "hello.rb.link")
=> 0

[root@master workspace]# ll
total 28
drwxr-xr-x. 2 root    root      6 Aug 12 20:45 crystal_learning
-rwxrwxrwx. 1 root    root     68 Jul 30 22:46 hello
-rw-r--r--. 1 looking looking  87 Aug 15 22:08 hello.rb
lrwxrwxrwx. 1 root    root      8 Aug 15 22:56 hello.rb.link -> hello.rb

File::symlink?( path)

如果 path 是一个符号链接,则返回 true。

# Ruby
[116] pry(main)> File::symlink?("hello.rb")
=> false
[117] pry(main)> File::symlink?("hello.rb.link")
=> true

File::truncate( path, len)

截断指定的文件为 len 字节。

# Ruby
[root@master workspace]# cat hello.rb
#!/usr/bin/env ruby
ARGV.each do |item|
  puts "Hello, #{item}"
end

[120] pry(main)> File::truncate("hello.rb", 50)
=> 0

[root@master workspace]# cat hello.rb
#!/usr/bin/env ruby
ARGV.each do |item|
  puts "He

File::umask([ mask])

如果未指定参数,则为该进程返回当前的 umask。如果指定了一个参数,则设置了 umask,并返回旧的 umask。

# Ruby
[122] pry(main)> File::umask()
=> 18

File::utime( atime, mtime, path...)

改变指定文件的访问和修改时间。

# Ruby
[123] pry(main)> File::atime("hello.rb")
=> 2020-08-15 22:59:38 +0800
[124] pry(main)> File::mtime("hello.rb")
=> 2020-08-15 22:59:31 +0800
[127] pry(main)> atime = File::atime("hello.rb") + 1800
=> 2020-08-15 23:29:38 +0800
[128] pry(main)> mtime = File::atime("hello.rb") + 3600
=> 2020-08-15 23:59:38 +0800

[129] pry(main)> File::utime(atime, mtime, "hello.rb")
=> 1

[130] pry(main)> File::mtime("hello.rb")
=> 2020-08-15 23:59:38 +0800
[131] pry(main)> File::atime("hello.rb")
=> 2020-08-15 23:29:38 +0800

File::writable?(path)

如果 path 是可写的,则返回 true。

# Ruby
[133] pry(main)> File::writable?("hello.rb")
=> true

File::write(path, content)

[6] pry(main)> File::write("test.txt", "hello world\nice to meet you")
=> 27
[7] pry(main)> File::read("test.txt")
=> "hello world\nice to meet you"

File::writable_real?( path)

如果 path 通过真正的用户权限是可写的,则返回 true。

# Ruby
[135] pry(main)> File::writable_real?("hello.rb")
=> true

File::zero?( path)

如果 path 的文件大小是 0,则返回 true,文件不存在则返回 false

# Ruby
[136] pry(main)> File::zero?("hello.rb")
=> false
[137] pry(main)> File::zero?("test.txt")
=> true

Dir 操作

Dir::glob( pat)

返回一个数组,包含与指定的通配符模式 pat 匹配的文件名:

  • * - 匹配包含 null 字符串的任意字符串
  • ** - 递归地匹配任意字符串
  • ? - 匹配任意单个字符
  • [...] - 匹配封闭字符中的任意一个
  • {a,b...} - 匹配字符串中的任意一个

Dir["foo.*"] # 匹配 "foo.c"、 "foo.rb" 等等
Dir["foo.?"] # 匹配 "foo.c"、 "foo.h" 等等

# Ruby
[149] pry(main)> Dir.glob("*")
=> ["world",
 "hello",
 "ruby_learning",
 "crystal_learning",
 "python3_learning",
 "ip-address.py",
 "test.py",
 "world.py",
 "hello.rb.bak",
 "hello.rb",
 "hello.rb.link",
 "test.txt",
 "test_dir"]
[150] pry(main)> Dir::glob("hello.*")
=> ["hello.rb.bak", "hello.rb", "hello.rb.link"]
[151] pry(main)> Dir["hello.*"]
=> ["hello.rb.bak", "hello.rb", "hello.rb.link"]
[152] pry(main)> Dir["*_*"]
=> ["ruby_learning", "crystal_learning", "python3_learning"]

使用 File::FNM_DOTMATCH 可以匹配隐藏文件:

Dir.glob("**/*", File::FNM_DOTMATCH)

Dir::pwd [and] Dir::getwd

获取当前目录。

# Ruby
[153] pry(main)> Dir::pwd
=> "/root/workspace"
[154] pry(main)> Dir::chdir("ruby_learning")
=> 0
[155] pry(main)> Dir::getwd
=> "/root/workspace/ruby_learning"
[156] pry(main)> Dir::chdir("../")
=> 0
[157] pry(main)> Dir::getwd
=> "/root/workspace"

Dir::chdir( path) 

改变当前目录。

# Ruby
[153] pry(main)> Dir::pwd
=> "/root/workspace"
[154] pry(main)> Dir::chdir("ruby_learning")
=> 0
[155] pry(main)> Dir::pwd
=> "/root/workspace/ruby_learning"

Dir::children(path) 

返回目录下的文件名(除了 . 和 ..),可以注意一下和 Dir::glob 和 Dir::entries 的区别。

# Ruby
[5] pry(main)> Dir.entries('./python3_learning')
=> [".", "..", "world.py", "ip-address.py", "test.txt", "test2.py", "test.py", "my-testfile", "minio_client.py"]
[6] pry(main)> Dir.children('./python3_learning')
=> ["world.py", "ip-address.py", "test.txt", "test2.py", "test.py", "my-testfile", "minio_client.py"]

Dir::chroot( path)

改变根目录(只允许超级用户)。并不是在所有的平台上都可用。

# Ruby
[1] pry(main)> Dir::pwd
=> "/root/workspace"
[2] pry(main)> Dir::chroot("/root")
[3] pry(main)> Dir::pwd
=> "/workspace"

Dir::entries( path)

返回一个数组,包含目录 path 中的文件名

# Ruby
[4] pry(main)> Dir::entries(".")
=> [".",
 "..",
 "world",
 "hello",
 "ruby_learning",
 "crystal_learning",
 "python3_learning",
 "ip-address.py",
 "test.py",
 "world.py",
 "hello.rb.bak",
 "hello.rb",
 "hello.rb.link",
 "test.txt"]
[5] pry(main)> Dir::entries("./ruby_learning")
=> [".", "..", "hello.rb", "test.txt"]

Dir::empty?(path) 

目录路径是否为空。

[1] pry(main)> Dir::empty?("test_dir")
=> true
[2] pry(main)> Dir::empty?("dir")
Errno::ENOENT: No such file or directory @ rb_dir_s_empty_p - dir
from (pry):2:in `empty?'

Dir::exist?(path) 

目录路径是否存在。

[3] pry(main)> Dir::exist?("test_dir")
=> true
[4] pry(main)> Dir::exist?("dir")
=> false

Dir::mkdir( path[, mode=0777])

创建 path 指定的目录。

# Ruby
[158] pry(main)> Dir::mkdir("test_dir")
=> 0
[159] pry(main)> Dir::chdir("test_dir")
=> 0
[160] pry(main)> Dir::getwd
=> "/root/workspace/test_dir"

Dir::foreach( path) {| f| ...}

返回 path 的新目录对象。

# Ruby
[2] pry(main)> Dir::foreach("ruby_learning"){|item| puts item}
.
..
hello.rb
test.txt
=> nil

# 下面这俩的合体
# [169] pry(main)> dir_obj = Dir::open("ruby_learning")
# [170] pry(main)> dir_obj.each{|item| puts item}

Dir::new( path)

返回 path 的新目录对象。

# Ruby
[163] pry(main)> Dir::new("test_dir")
=> #<Dir:test_dir>

Dir::open( path){| dir| ...}

如果 open 给出一个块,则新目录对象会传到该块,块会在终止前关闭目录对象。

# Ruby
[169] pry(main)> dir_obj = Dir::open("ruby_learning")
=> #<Dir:ruby_learning>
# dir_obj.each
[170] pry(main)> dir_obj.each{|item| puts item}
.
..
hello.rb
test.txt
=> #<Dir:ruby_learning>

------------------------------------------------------------
# dir_obj.read
[172] pry(main)> dir_obj = Dir::open("ruby_learning")
=> #<Dir:ruby_learning>
[173] pry(main)> dir_obj.read
=> "."
[174] pry(main)> dir_obj.read
=> ".."
[175] pry(main)> dir_obj.read
=> "hello.rb"

------------------------------------------------------------
# dir_obj.close
[176] pry(main)> dir_obj.close
=> nil
[177] pry(main)> dir_obj.read
IOError: closed directory
from (pry):189:in "read"

------------------------------------------------------------
# dir_obj.rewind
[178] pry(main)> dir_obj = Dir::open("ruby_learning")
=> #<Dir:ruby_learning>
[179] pry(main)> dir_obj.read
=> "."
[180] pry(main)> dir_obj.read
=> ".."
[181] pry(main)> dir_obj.read
=> "hello.rb"
[182] pry(main)> dir_obj.rewind
=> #<Dir:ruby_learning>
[183] pry(main)> dir_obj.read
=> "."
[184] pry(main)> dir_obj.read
=> ".."

------------------------------------------------------------
# dir_obj.tell [or] dir_obj.pos
[185] pry(main)> dir_obj.tell
=> 12
[186] pry(main)> dir_obj.pos
=> 12
[187] pry(main)> dir_obj.read
=> "hello.rb"
[188] pry(main)> dir_obj.pos
=> 15
[189] pry(main)> dir_obj.tell
=> 15

------------------------------------------------------------
# dir_obj.seek
[190] pry(main)> dir_obj.seek(15)
=> #<Dir:ruby_learning>

Dir::rmdir( path) [or] Dir::unlink( path) [or] Dir::delete( path)

删除 path 指定的目录。目录必须是空的。

# Ruby
[166] pry(main)> Dir::rmdir("test_dir")
=> 0

 类似资料: