Ruby 的 File 類
本章將詳細介紹如何在 Ruby 中創(chuàng)建,打開以及讀取和寫入文件。然后,我們將學習如何刪除和重命名文件。
1. 使用 Ruby 創(chuàng)建一個文件
使用 File
類的 new
方法在 Ruby 中創(chuàng)建新文件。新方法接受兩個參數,第一個是要創(chuàng)建的文件的名稱,第二個是打開文件的模式。下表顯示了受支持的文件模式。
模式 | 時機簡介(調用的時機) |
---|---|
r | 只讀訪問。指針位于文件的開頭。 |
r+ | 讀寫訪問。指針位于文件的開頭。 |
w | 只寫訪問。指針位于文件的開頭。 |
w+ | 讀寫訪問。指針位于文件的開頭。 |
a | 只寫訪問。指針位于文件末尾 |
a+ | 讀寫訪問。指針位于文件末尾 |
b | 二進制文件模式。與以上模式結合使用。僅Windows / DOS |
結合以上信息,我們在只寫模式下創(chuàng)建一個新文件。
實例:
File.new("temp.txt", "w")
=> #<File:temp.txt>
2. 打開現有文件
可以使用 File
類的 open
方法打開現有文件:
實例:
file = File.open("temp.txt")
=> #<File:temp.txt>
請注意,可用上表概述的不同模式打開現有文件。例如,我們可以以只讀模式打開文件:
file = File.open("temp.txt", "r")
=> #<File:temp.txt>
還可以使用 closed?
來確定文件是否已經打開:
file.closed?
=> false
最后,我們可以使用 Ruby File
類的 close
方法關閉文件:
file = File.open("temp.txt", "r")
=> #<File:temp.txt>
file.close
=> nil
3. 在 Ruby 中重命名和刪除文件
在 Ruby 中,分別使用 rename
和 delete
方法來重命名和刪除文件。例如,我們可以創(chuàng)建一個新文件,重命名然后刪除它。
File.new("tempfile.txt", "w")
=> #<File:tempfile.txt>
File.rename("tempfile.txt", "newfile.txt")
=> 0
File.delete("newfile.txt")
=> 1
4. 獲取有關文件的信息
文件處理通常不僅僅需要打開文件。有時有必要在打開文件之前先找到有關文件的信息。File
類為此目的提供了一系列方法。
要查找文件是否已存在,請使用exists?
方法。
File.exists?("temp.txt")
=> true
要確定文件是否真的是文件而不是目錄,請使用file?
方法。
File.file?("ruby")
=> false
同樣,找出它是否是目錄,請使用directory?
方法。
File.directory?("ruby")
=> true
要確定文件是可讀,可寫還是可執(zhí)行的請使用readable?
,writeable?
和executable?
方法。
File.readable?("temp.txt")
=> true
File.writable?("temp.txt")
=> true
File.executable?("temp.txt")
=> false
使用size
方法獲取文件的大小。
File.size("temp.txt")
=> 99
查找文件是否為零的空文件(即長度為零)使用zero?
。
File.zero?("temp.txt")
=> false
使用ftype
方法找出文件的類型。
File.ftype("temp.txt")
=> "file"
File.ftype("../ruby")
=> "directory"
File.ftype("/dev/sda5")
=> "blockSpecial"
最后我們可以使用ctime
,mtime
和atime
來找出創(chuàng)建,修改和訪問時間。
File.ctime("temp.txt")
=> Thu Nov 29 10:51:18 EST 2007
File.mtime("temp.txt")
=> Thu Nov 29 11:14:18 EST 2007
File.atime("temp.txt")
=> Thu Nov 29 11:14:19 EST 2007
5. 讀寫文件
打開現有文件或創(chuàng)建新文件后,我們需要能夠讀取和寫入該文件。我們可以使用 readline
從文件讀取行。
myfile = File.open("temp.txt")
=> #<File:temp.txt>
myfile.readline
=> "This is a test file\n"
myfile.readline
=> "It contains some example lines\n"
另外,我們可以使用each
方法讀取整個文件。
myfile = File.open("temp.txt")
=> #<File:temp.txt>
myfile.each {|line| print line }
This is a test file
It contains some example lines
But other than that
It serves no real purpose
也可以使用getc
方法逐個字符地從文件中提取數據。
myfile = File.open("Hello.txt")
=> #<File:temp.txt>
myfile.getc.chr
=> "H"
myfile.getc.chr
=> "e"
myfile.getc.chr
=> "l"
我們還可以使用putc
方法寫入文件,一次寫入一個字符,或者使用puts
方法一次寫入一個字符串-請注意rewind
方法調用的重要性。這會將文件指針移回文件的開頭,因此我們可以閱讀所寫內容。
myfile = File.new("write.txt", "w+") # 讀寫模式打開文件
=> #<File:write.txt>
myfile.puts("This test line 1") # 寫入第一行
=> nil
myfile.puts("This test line 2") # 寫入第二行
=> nil
myfile.rewind # 將指針移動到開頭
=> 0
myfile.readline
=> "This test line 1\n"
myfile.readline
=> "This test line 2\n"
6. 小結
本章節(jié)我們學習了如何使用 File.new
創(chuàng)建文件,文件模式,File.open
打開文件,File.rename
重命名文件,File.delete
刪除文件,各種獲取文件信息的方法以及文件讀寫的方法。