路漫漫其修远兮,吾将上下而求索

ruby读取目录和文件的file/directories类

上一篇 / 下一篇  2009-12-16 11:42:13 / 个人分类:Ruby_Watir

Directories in Ruby:

All files are contained within various directories, and Ruby has no problem handling these too. Whereas theFileclass handles files, directories are handled with theDirclass.

所有的文件都是包含在各种不同的目录中,RUBY能够很好的处理它。File类处理文件,Dir类处理目录

Navigating Through Directories:

To change directory within a Ruby program, useDir.chdiras follows. This example changes the current directory to/usr/bin.

使用Dir.chdir来改变当前目录

Dir.chdir("/usr/bin")

You can find out what the current directory is withDir.pwd:

使用Dir.pwd来查看当前目录

puts Dir.pwd # This will return something like /usr/bin

You can get a list of the files and directories within a specific directory usingDir.entries:

使用Dir.entries来查看一个特定目录下的所有文件

puts Dir.entries("/usr/bin").join(' ')

Dir.entriesreturns an array with all the entries within the specified directory.Dir.foreachprovides the same feature:

Dir.entries 将以数组的形式放回特定目录下的所有文件,Dir.foreach也可以这样做

Dir.foreach("/usr/bin") do |entry|
   puts entry
end

An even more concise way of getting directory listings is by using Dir's class array method:

 

Dir["/usr/bin/*"]

Creating a Directory:

TheDir.mkdircan be used to create directories:

Dir.mkdir("mynewdir")

You can also set permissions on a new directory (not one that already exists) with mkdir:

NOTE:The mask 755 sets permissions owner, group, world [anyone] to rwxr-xr-x where r = read, w = write, and x = execute.

Dir.mkdir( "mynewdir", 755 )

Deleting a Directory:

TheDir.deletecan be used to delete a directory. TheDir.unlinkandDir.rmdirperform. exactly the same function and are provided for convenience.

Dir.delete("testdir")

Creating Files & Temporary Directories:

Temporary files are those that might be created briefly during a program's execution but aren't a permanent store of information.

Dir.tmpdirprovides the path to the temporary directory on the current system, although the method is not available by default. To makeDir.tmpdiravailable it's necessary to use require 'tmpdir'.

You can useDir.tmpdirwithFile.jointo create a platform-independent temporary file:

require 'tmpdir'
   tempfilename = File.join(Dir.tmpdir, "tingtong")
   tempfile = File.new(tempfilename, "w")
   tempfile.puts "This is a temporary file"
   tempfile.close
   File.delete(tempfilename)

This code creates a temporary file, writes data to it, and deletes it. Ruby's standard library also includes a library calledTempfilethat can create temporary files for you:

require 'tempfile'
   f = Tempfile.new('tingtong')
   f.puts "Hello"
   puts f.path
   f.close

 

TheputsStatement:

In previous chapters, you assigned values to variables and then printed the output usingputsstatement.

Theputsstatement instructs the program to display the value stored in the variable. This will add a new line at the end of each line it writes.

Example:

#!/usr/bin/ruby

val1 = "This is variable one"
val2 = "This is variable two"
puts val1
puts val2

This will produce following result:

This is variable one
This is variable two

ThegetsStatement:

Thegetsstatement can be used to take any input from the user from standard screen called STDIN.

Example:

The following code shows you how to use the gets statement. This code will prompt the user to enter a value, which will be stored in a variable val and finally will be printed on STDOUT.

#!/usr/bin/ruby

puts "Enter a value :"
val = gets
puts val

This will produce following result:

Enter a value :
This is entered value
This is entered value

TheputcStatement:

Unlike theputsstatement, which outputs the entire string onto the screen, theputcstatement can be used to output one character at a time.

Example:

The output of the following code is just the character H:

#!/usr/bin/ruby

str="Hello Ruby!"
putc str

This will produce following result:

H

TheprintStatement:

Theprintstatement is similar to theputsstatement. The only difference is that theputsstatement goes to the next line after printing the contents, whereas with theprintstatement the cursor is positioned on the same line.

Example:

#!/usr/bin/ruby

print "Hello World"
print "Good Morning"

This will produce following result:

Hello WorldGood Morning

Opening and Closing Files:

Until now, you have been reading and writing to the standard input and output. Now we will see how to play with actual data files.

TheFile.newMethod:

You can create aFileobject usingFile.newmethod for reading, writing, or both, according to the mode string. Finally you can useFile.closemethod to close that file.

Syntax:

aFile = File.new("filename", "mode")
   # ... process the file
aFile.close

TheFile.openMethod:

You can useFile.openmethod to create a new file object and assign that file object to a file. However, there is one difference in betweenFile.openandFile.newmethods. The difference is that theFile.openmethod can be associated with a block, whereas you cannot do the same using theFile.newmethod.

File.open("filename", "mode") do |aFile|
   # ... process the file
end

Here is a list of The Different Modes of Opening a File:

ModesDescription
rRead-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+Read-write mode. The file pointer will be at the beginning of the file.
wWrite-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
aWrite-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Reading and Writing Files:

The same methods that we've been using for 'simple' I/O are available for all file objects. So, gets reads a line from standard input, andaFile.getsreads a line from the file object aFile.

However, I/O objects provides additional set of access methods to make our lives easier.

ThesysreadMethod:

You can use the methodsysreadto read the contents of a file. You can open the file in any of the modes when using the method sysread. For example :

#!/usr/bin/ruby

aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")
if aFile
   content = aFile.sysread(20)
   puts content
else
   puts "Unable to open file!"
end

This statement will output the first 20 characters of the file. The file pointer will now be placed at the 21st character in the file.

ThesyswriteMethod:

You can use the method syswrite to write the contents into a file. You need to open the file in write mode when using the method syswrite. For example :

#!/usr/bin/ruby

aFile = File.new("/var/www/tutorialspoint/ruby/test", "r+")
if aFile
   aFile.syswrite("ABCDEF")
else
   puts "Unable to open file!"
end

This statement will write "ABCDEF" into the file.

Theeach_byteMethod:

This method belongs to the classFile. The methodeach_byteis always associated with a block. Consider the following code sample: :

#!/usr/bin/ruby

aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")
if aFile
   aFile.syswrite("ABCDEF")
   aFile.each_byte {|ch| putc ch; putc ?. }
else
   puts "Unable to open file!"
end

Characters are passed one by one to the variable ch and then displayed on the screen as follows:

T.h.i.s. .i.s. .l.i.n.e. .o.n.e.
.T.h.i.s. .i.s. .l.i.n.e. .t.w.o.
.T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e.
.A.n.d. .s.o. .o.n.......

TheIO.readlinesMethod:

The classFileis a subclass of the class IO. The class IO also has some methods which can be used to manipulate files.

One of the IO class methods isIO.readlines. This method returns the contents of the file line by line. The following code displays the use of the methodIO.readlines:

#!/usr/bin/ruby

arr = IO.readlines("/var/www/tutorialspoint/ruby/test")
puts arr[0]
puts arr[1]

In this code, the variable arr is an array. Each line of the filetestwill be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file.

TheIO.foreachMethod:

This method also returns output line by line. The difference between the methodforeachand the methodreadlinesis that the methodforeachis associated with a block. However, unlike the methodreadlines, the methodforeachdoes not return an array. For example:

#!/usr/bin/ruby

IO.foreach("test"){|block| puts block}

This code will pass the contents of the filetestline by line to the variable block, and then the output will be displayed on the screen.

Renaming and Deleting Files:

You can rename and delete files programmatically with Ruby with therenameanddeletemethods.

Following is the example to rename an existing filetest1.txt:

#!/usr/bin/ruby

# Rename a file from test1.txt to test2.txt
File.rename( "test1.txt", "test2.txt" )

Following is the example to delete an existing filetest2.txt:

#!/usr/bin/ruby

# Delete file test2.txt
File.delete("text2.txt")

File Modes and Ownership:

Use thechmodmethod with a mask to change the mode or permissions/access list of a file:

Following is the example to change mode of an existing filetest.txtto a mask value:

#!/usr/bin/ruby

file = File.new( "test.txt", "w" )
file.chmod( 0755 )

Following is the table which can help you to choose different mask forchmodmethod:

MaskDescription
0700rwx mask for owner
0400r for owner
0200w for owner
0100x for owner
0070rwx mask for group
0040r for group
0020w for group
0010x for group
0007rwx mask for other
0004r for other
0002w for other
0001x for other
4000Set user ID on execution
2000Set group ID on execution
1000Save swapped text, even after use

File Inquiries:

The following command tests whether a file exists before opening it:

#!/usr/bin/ruby

File.open("file.rb") if File::exists?( "file.rb" )

The following command inquire whether the file is really a file:

#!/usr/bin/ruby

# This returns eithertrueorfalseFile.file?( "text.txt" )

The following command finds out if it given file name is a directory:

#!/usr/bin/ruby

# a directory
File::directory?( "/usr/local/bin" ) # => true

# a file
File::directory?( "file.rb" ) # => false

The following command finds whether the file is readable, writable or executable:

#!/usr/bin/ruby

File.readable?( "test.txt" )   # => true
File.writable?( "test.txt" )   # => true
File.executable?( "test.txt" ) # => false

The following command finds whether the file has zero size or not:

#!/usr/bin/ruby

File.zero?( "test.txt" )      # => true

The following command returns size of the file :

#!/usr/bin/ruby

File.size?( "text.txt" )     # => 1002

The following command can be used to find out a type of file :

#!/usr/bin/ruby

File::ftype( "test.txt" )     # => file

The ftype method identifies the type of the file by returning one of the following:file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.

The following command can be used to find when a file was created, modified, or last accessed :

#!/usr/bin/ruby

File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008
File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008
File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-14  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 40519
  • 日志数: 76
  • 图片数: 2
  • 建立时间: 2007-11-02
  • 更新时间: 2011-08-13

RSS订阅

Open Toolbar