由于ruby的轻巧灵敏,使得它读写文件操作变的很方便简单,下面就个人的2个小例子来分别介绍一下ruby中基本的读写文件操作:
1.读文件:
print "Please input a file name: "
filename=gets
if filename&&!filename.empty?
filename=filename[0, filename.length-1]
else
print "The file name cat't bean null!!"
exit(1)
end
if File.exist?(filename)
puts "==================#{filename}====================="
File.open(filename, "r") do |file|
while line=file.gets
puts line
end
end
puts "================================================"
else
puts "The program can't find the file that name was '#{filename}'."
end
print "Press any key to continue...."
gets
大家应该注意到真正的代码只有几行,就是其中的open方法在操作,它为我们实现了打开文件和并闭文件的操作,我们只需并心操作代码的实现,这样使得操作文件变的很方便。另外如果想直接以文件的行为单位来操作文件可用“file.each_line{ |line| 操作代码 }”的行式,是不是很方便!!
2.写文件:
puts "======================================"
puts "This program is about Ruby write file."
puts "======================================"
print "Please input file name: "
filename=gets
if filename&&!filename.empty?
filename=filename[0, filename.length-1]
else
puts "The file name can't been null!!"
exit 1;
end
file=nil
unless File.exist?(filename)
puts "The system cannot find the file specified!"
print "[C] to create a new file and [E] to exit the program: "
option=gets
if option&&!option.empty?
option=option.chomp
else
puts "bye!"
exit 1;
end
case option.downcase
when "c" : file=File.new(filename, "w")
when "e" : exit 0
else
puts "Invalid arguments!! The program has stop. "
exit 0
end
else
file=File.new(filename, "w")
end
print "Now please input content: "
content=gets
file.print content
file.close
print "Press any key to continue...."
gets
在ruby中创建文件不用显示的指出,只需以"w"写的方式打开文件就可,其它的也是由ruby完成的,也就是说如果所指定的文件不存在ruby则自动创建,可用File.exist?(filename)来判断指定的文件是否存在,但如果是创建目录呢?通过查找API知道可用Dir类的mkdir方法实现!更多的方法请参见官方的API,呵呵...
在上面的二个例子中特别要注意gets方法,它从控制台中读入一行子符串时,后面会跟一个换行符,所以在以其来创建文件对象时要将其除去.