首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Ruby 常用檔案操作方法完整指南:建立、讀寫、刪除、重命名、目錄管理

     編輯:更多程式設計知識

Ruby 提供直觀強大的 File、Dir、IO 類別進行檔案系統操作。本文系統整理新建檔案、讀取、刪除/重命名、目錄操作、檔案資訊查詢、尋找檔案、複製比較等核心功能,附完整程式碼範例。

1. 新建檔案與寫入


# 模式: "r" 唯讀, "r+" 讀寫, "w" 唯寫(截斷), "w+" 讀寫(截斷), "a" 附加, "a+" 讀寫附加, "b" 二進位
f = File.new(File.join("C:", "Test.txt"), "w+")
f.puts("I am Jack")
f.puts("Hello World")
f.close

# 區塊形式自動關閉
File.open("test.txt", "w") do |f|
  f.puts "Line 1"
  f.write "No newline"
end

2. 讀取檔案


# 逐行讀取
File.open("test.txt", "r") do |f|
  f.each_line { |line| puts "#{f.lineno}: #{line}" }
end

# 一次讀全檔
content = File.read("test.txt")
lines = File.readlines("test.txt")  # 含換行符的陣列

3. 刪除、重命名、存在性檢查


File.new("books.txt", "w")      # 建立
File.rename("books.txt", "chaps.txt")
File.delete("chaps.txt")        # 同 File.unlink

File.exist?("test.txt")         # true/false
File.file?("test.txt")          # 是否為檔案
File.directory?("C:/ruby")      # 是否為目錄

4. 目錄操作


Dir.mkdir("c:/testdir")         # 建立目錄
Dir.rmdir("c:/testdir")         # 刪除空目錄

# 列出目錄內容
Dir.entries("C:/ruby").each { |e| puts e }

# 遞迴走訪
require 'find'
Find.find('.') { |path| puts path }

5. 檔案資訊查詢


f = "cnblogslink.txt"
File.readable?(f)    # true
File.writable?(f)    # true
File.executable?(f)  # false
File.zero?(f)        # false (非空)
File.size(f)         # 74 bytes
File.ftype(f)        # "file"
File.ctime(f)        # 建立時間
File.mtime(f)        # 修改時間
File.atime(f)        # 最後存取時間

6. 尋找檔案


# 所有檔案
Dir["c:/ruby/*"].each { |x| puts x }

# 特定類型
Dir["*.rb"].each { |x| puts x }

# 正則篩選
Dir["c:/ruby/**/*.rb"].each { |x| puts x }  # ** 遞迴 (Ruby 2.0+)

# 遞迴尋找 (Find 模組)
require 'find'
Find.find('/etc', '/var', '.') do |f|
  Find.prune if f == '.'  # 跳過當前目錄遞迴
  puts f
end

7. ARGV 與 ARGF 處理命令列檔案


# ARGV: 命令列參數陣列
ARGV << "cnblogslink.txt"
while line = gets   # 從 ARGV 檔案讀取
  print line
end

# ARGF: 虛擬檔案,串接所有 ARGV 檔案
ARGF.each_line { |line| print line }

8. 檔案複製與比較


require 'ftools'  # Ruby 1.8 / 1.9 需 require 'fileutils'
FileUtils.cp('testfile', 'testfile1')
FileUtils.cmp('testfile', 'testfile1')  # 內容比較

9. StringIO 記憶體檔案操作


require 'stringio'
io = StringIO.new("abc\ndef\n123")
io.seek(4)          # 移至位移 4
io.puts("XYZ")      # 覆寫
puts io.string      # 取得完整字串

總結

Ruby 的檔案操作 API 設計極具可讀性:File 處理單一檔案、Dir 處理目錄、IO 統一輸入輸出介面、Find 遞迴搜尋、FileUtils 高階工具。善用區塊形式(File.open { |f| ... })確保資源自動釋放,是撰寫健壯 Ruby 腳本的關鍵習慣。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved