一、
新建文件
| f= File . new ( File .join( "C:" , "Test.txt" ), "w+" ) |
文件模式
"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 . new ( "books.txt" , "w" ) |
| File .rename( "books.txt" , "chaps.txt" ) |
| File .delete( "chaps.txt" ) |
四、目录操作
05 | Dir .rmdir( "c:/testdir" ) |
08 | p Dir .entries( File .join( "C:" , "Ruby" )).join( ' ' ) |
11 | Dir .entries( File .join( "C:" , "Ruby" )). each { |
1、ARGV and ARGF
ARGV
| ARGV << "cnblogslink.txt" |
| #The gets method is a Kernel method that gets lines from ARGV |
ARGF
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 |
| p File .executable?( "cnblogslink.txt" ) # => false |
| p File .zero?( "cnblogslink.txt" ) # => false |
| p File .size?( "cnblogslink.txt" ) # => 74 |
| p File .size( "cnblogslink.txt" ) # => 74 |
| p File : :ftype ( "cnblogslink.txt" ) # => "file" |
| p File : :ctime ( "cnblogslink.txt" ) # => Sat Sep 19 08:05:07 +0800 2009 |
| p File : :mtime ( "cnblogslink.txt" ) # => Sat Sep 19 08:06:34 +0800 2009 |
| p File : :atime ( "cnblogslink.txt" ) # => Sat Sep 19 08:05:07 +0800 2009 |
3、查找文件
| Dir [ "c:/ruby/*" ]. each {|x| |
| |x| puts x if x != "." && x != ".." |
| Dir .open( 'c:/ruby' ) { |d| d.grep /l/ }. each {|x| puts x} |
| puts "---------------------------" |
| Dir [ "c:/ruby/ruby/[rs]*" ]. each {|x| puts x} |
| puts "------------------------" |
| Dir [ "c:/ruby/[^s]*" ]. each {|x| puts x} |
| puts "------------------------" |
| Dir [ "c:/ruby/{ruby,li}*" ]. each {|x| puts x} |
| puts "------------------------" |
| Dir [ "c:/ruby/?b*" ]. each {|x| puts x} |
| Find.find( './' ) { |path| puts path } |