26 Ruby 的 File 類
本章將詳細介紹如何在 Ruby 中建立,開啟以及讀取和寫入檔案。然後,我們將學習如何刪除和重新命名檔案。
1. 使用 Ruby 建立一個檔案
使用 File
類的 new
方法在 Ruby 中建立新檔案。新方法接受兩個引數,第一個是要建立的檔案的名稱,第二個是開啟檔案的模式。下表顯示了受支援的檔案模式。
模式 | 時機簡介(呼叫的時機) |
---|---|
r | 只讀訪問。指標位於檔案的開頭。 |
r+ | 讀寫訪問。指標位於檔案的開頭。 |
w | 只寫訪問。指標位於檔案的開頭。 |
w+ | 讀寫訪問。指標位於檔案的開頭。 |
a | 只寫訪問。指標位於檔案末尾 |
a+ | 讀寫訪問。指標位於檔案末尾 |
b | 二進位制檔案模式。與以上模式結合使用。僅Windows / DOS |
結合以上資訊,我們在只寫模式下建立一個新檔案。
例項:
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
方法來重新命名和刪除檔案。例如,我們可以建立一個新檔案,重新命名然後刪除它。
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
要確定檔案是可讀,可寫還是可執行的請使用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
來找出建立,修改和訪問時間。
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. 讀寫檔案
開啟現有檔案或建立新檔案後,我們需要能夠讀取和寫入該檔案。我們可以使用 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. 小結
本章節我們學習瞭如何使用 File.new
建立檔案,檔案模式,File.open
開啟檔案,File.rename
重新命名檔案,File.delete
刪除檔案,各種獲取檔案資訊的方法以及檔案讀寫的方法。