一、
建立檔案
f=File.new(File.join("C:","Test.txt"), "w+")f.puts("I am Jack")f.puts("Hello World")
檔案模式
"r" :Read-only. Starts at beginning of file (default mode).
"r+" :Read-write. Starts at beginning of file.
"w" :Write-only. Truncates existing file to zero length or creates a new file for writing.
"w+" :Read-write. Truncates existing file to zero length or creates a new file for reading and writing.
"a" :Write-only. Starts at end of file if file exists; otherwise, creates a new file for writing.
"a+" :Read-write. Starts at end of file if file exists; otherwise, creates a new file for reading and writing.
"b" :(DOS/Windows only.) Binary file mode. May appear with any of the key letters listed above
二、讀取檔案
file=File.open(File.join("C:","Test.txt"),"r")file.each { |line| print "#{file.lineno}.", line }file.close
輸出:
1.白日依山盡
2.黃河入海流
3.欲窮千裡目
4.更上一層樓
三、建立、刪除、重新命名檔案
File.new( "books.txt", "w" )File.rename( "books.txt", "chaps.txt" )File.delete( "chaps.txt" )
三、目錄操作
建立目錄Dir.mkdir("c:/testdir")#刪除目錄Dir.rmdir("c:/testdir")#查詢目錄裡的檔案p Dir.entries(File.join("C:","Ruby")).join(' ')#遍曆目錄Dir.entries(File.join("C:","Ruby")).each { |e| puts e}
輸出:
"C:/studyruby""c:/ruby"
查看目錄資訊
d:\Study\rubysample>irbirb(main):001:0> dir=Dir.open( File.join("C:","Ruby") )=> #irb(main):002:0> dir.path=> "C:/Ruby"irb(main):003:0> dir.tell=> 0irb(main):004:0> dir.read=> "."irb(main):005:0> dir.rewind=> #irb(main):006:0> dir.each{|e| puts e}...binChangeLog.txtdoclibLICENSE.txtmanMANIFESTmiscREADME.1stReleaseNotes.txtruby.icorubyopt.delrubyw.icosamplesscitesharesrcuninstall.exe=> #irb(main):007:0>