ruby學習之文件和數據庫(一)

輸入輸出:

標準輸入:

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
  
end

f = 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")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章