ruby學習之檔案和資料庫(一)

來源:互聯網
上載者:User

輸入輸出:

標準輸入:

a = gets , gets是從標準輸入擷取一行資料 , lines = readlines 一次擷取多行內容直到EOF(ctrl+D)

puts a ,puts是列印輸出到標準輸出

 

檔案輸入輸出:

File類開啟檔案,可以是純文字和二進位檔案

File.open("text.txt").each{|line| puts line},File.open接受代碼塊,當代碼塊運行結束,檔案自動關閉

也可以File.new("text.txt","r").each{|line| puts line},File.new返迴文件對象,關閉檔案就必須用File.close

class MyFile  attr_reader :handle  def initialize(filename)    @handle = File.new(filename,"r")  end    def finished    @handle.close  end  endf = MyFile.new("D://rb//text.txt")puts f.handle.each{|txt| puts txt}f.finished

其中each的預設界定符是"\n",自訂用each(",")自訂為","界定

用each_byte方法,逐位元組地讀取I/O流。用chr方法轉化為字元~

 

另外用gets方法讀取

  def self.readf    File.open("D://rb//text.txt") do |f|      10.times{ puts f.gets}    end  end

同時也可以接受界定符 f.gets(',')  而f.getc是each_byte的非迭代版本

 

整行讀取

  def self.readl    puts File.open("D://rb//text.txt").readlines.join("--")  end

read方法讀取任意位元組數

  def self.readb    File.open("D://rb//text.txt") do |f|      puts f.read(6)    end  end

簡便方法推薦~

File.read(filename)和File.readlines(filename)

 

輸入:

File.open("text.txt","w") do |f|f.puts("this is a test")end

File.new檔案模式

檔案模式 操作
r 唯讀,檔案指標開頭
r+ 可讀可寫,檔案指標開頭,複寫
w 寫,複寫
w+ 可讀可寫,建立新檔案
a 寫(附加模式)
a+ 可讀可寫(附加模式)檔案指標末尾

gets-->puts

getc-->putc

read-->write

改名:File.rename("file1","file2")

刪除:File.delete("file1","file2".....)

比較相同:File.identical?("file1","file2")

組織檔案路勁:File.join('full','path','here','filename.txt')

上次修改檔案的時間:File.mtime("file1")

檔案是否存在:File.exist("file1")

檔案大小:File.size("file1")

檔案末尾:f.eof

檔案智鎮江定位:seek方法
seek三種模式

   
IO::SEEK_CUR 從當前位置向前移動N個位元組

IO::SEEK_END

移動到檔案末尾一定位置的地方。這表示從末尾開始搜尋,可能使用負數
IO::SEEK_SET 移動到檔案的絕對位置。與pos=完全相同
  def self.filepoint    f = File.new("D://rb//text.txt","r+")    f.seek(-5,IO::SEEK_END)    f.putc "X"    f.close  end

 

目錄處理:(File::SEPARATOR是斜杠)

顯示目前的目錄:Dir.pwd

移動目前的目錄:Dir.chdir("/usr/bin")

獲得目錄檔案清單:Dir.entries("/usr/bin").join('  '),返回一個數組。Dir.foreach同理。Dir["/usr/bin/*"]

建立目錄:Dir.mkdir("dir")

刪除目錄:Dir.delete("dir")

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.