深度解析Ruby文件操作
Ruby文件操作是一个比较常用的一个编程方法。在接下来的这篇文章中我们将会为大家详细介绍有关Ruby文件操作的一些实现技巧。
Ruby文件操作代码示例如下:
#2.rb;在同一级目录建立1.txt的文件,输入一些内容
file=File.open("1.txt","r")#file=File.open("F:\\ruby\\rb\\1.txt","r")绝对路径下
file.each_line do |line|
puts line
end
# another logic
File.open("1.txt","r") do |file|
while line=file.gets
puts line
end
end
# the third logic ,the code is copied from someone else ...
IO.foreach("1.txt") do |line|
#puts line if line =~/target/
puts line if line !~/target/
end
#count the number of a file ,the bytes and lines
arr=IO.read("1.txt")
bytes=arr.size
puts "the byte size is #{bytes}"
arrl=IO.readlines("1.txt")
lines = arrl.size
puts"the lines number is #{lines}"
#show the file's path
puts File.expand_path("1.txt")
#count chars from a file
file= File.new("1.txt")
w_count = 0
file.each_byte do |byte|
w_count += 1 if byte ==?1
end
puts "#{w_count}"
#create new file and write some words there
file= File.new("2.txt","w")
puts File.exist?("2.txt")#judge the file is exist or not
file.write("hehe\nhahah")
#io.stream operation
require 'stringio'
ios = StringIO.new("abcdef\n ABC \n 12345")
ios.seek(5)
ios.puts("xyz3")
puts ios.tell
puts ios.string.dump
#the result is 10,insert xyz3 at the 5th byte
#another example
require 'stringio'
ios = StringIO.new("abcdef\n ABC \n 12345")
ios.seek(3)
ios.ungetc(?w) #replace the char at index 3