一、新建文件
代码如下:
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
三、新建、删除、重命名文件
代码如下:
File.new( "books.txt", "w" )
File.rename( "books.txt", "chaps.txt" )
File.delete( "chaps.txt" )
四、目录操作
1 创建目录
代码如下:
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
}
1、ARGV and ARGF
代码如下:
ARGV
ARGV << "cnblogslink.txt"
#The gets method is a Kernel method that gets lines from ARGV
print while gets
p ARGV.class
ARGF
while line = ARGF.gets
print line
end
2、文件信息查询
代码如下:
#文件是否存在
p File::exists?( "cnblogslink.txt" ) # => true
#是否是文件
p File.file?( "cnblogslink.txt" ) # => true
#是否是目录
p File::directory?( "c:/ruby" ) # => true
p File::directory?( "cnblogslink.txt" ) # => false
#文件权限
p File.readable?( "cnblogslink.txt" ) # => true
p File.writable?( "cnblogslink.txt" ) # => true
新闻热点
疑难解答