发布于 2015-07-11 02:53:29 | 211 次阅读 | 评论: 0 | 来源: 网络整理

Ruby提供了一套完整的I/O相关的内核模块中实现方法。所有I/O方法来自IO类。

类IO提供了所有的基本方法,如 read, write, gets, puts, readline, getc 和 printf.

本章将涵盖所有可供在Ruby中使用的基本I/O功能。如需使用更多的功能,请参考Ruby的IO类。

puts 语句:

在前面的章节中,你指定值的变量和然后使用声明 puts 输出。

puts 把语句指示程序显示存储在变量值。这将添加一个新行,每行末尾写出(输出)。

例子:


#!/usr/bin/ruby

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

这将产生以下结果:


This is variable one
This is variable two

gets 语句:

 gets 语句可以用来从用户从标准屏幕采取输入调用 STDIN.

例如:

下面的代码显示了如何使用 gets 语句。此代码将提示用户输入一个值,将被存储在一个变量val,最后将打印在 STDOUT.


#!/usr/bin/ruby

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

这将产生以下结果:


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

putc 语句:

与 puts 语句不相同,它在屏幕上输出整个字符串,而putc 语句可以用来一次输出一个字符。

实例:

下面的代码的输出只是一个字符 H:


#!/usr/bin/ruby

str="Hello Ruby!"
putc str

这将产生以下结果:


H

 print 语句:

print 语句是类似 puts 语句。唯一的区别是,puts语句后进入到下一行打印的内容,print 语句将光标定位在同一行上。

实例:


#!/usr/bin/ruby

print "Hello World"
print "Good Morning"

这将产生以下结果:


Hello WorldGood Morning

打开和关闭文件:

到现在为止,我们已经可以读取和写入的标准输入和输出。我们将看看如何运用到实际的数据文件。

File.new 方法:

可以创建一个的File对象使用File.new方法的读,写或两者兼有,这需要根据模式串。最后,可以使用File.close的方法来关闭该文件。

语法:


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

File.open 方法:

可以使用File.open方法的方法来创建一个新的文件对象,并分配到一个文件中,文件对象。然而,File.open方法和File.new方法之间区别。 File.open方法不同的是,可以关联一个块,而不能在File.new方法使用。


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

这里是一个不同的模式打开文件列表:

模式 描述
r Read-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.
w Write-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.
a Write-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.

读取和写入文件:

同样的方法,我们一直在使用“简单”的I/O所有文件对象。因此,gets 从标准输入读取一行,File.gets文件从文件对象读取一行。

然而,I/O对象提供额外的访问方法,使我们的生活更轻松。

sysread 方法:

可以使用该方法sysread读取一个文件的内容。可以打开该文件时,在任何模式中使用的方法sysread。例如:

以下是输入文本文件:


This is a simple text file for testing purpose.

现在,让我们尝试读取这个文件:


#!/usr/bin/ruby

aFile = File.new("input.txt", "r")
if aFile
   content = aFile.sysread(20)
   puts content
else
   puts "Unable to open file!"
end

这条语句将输出文件的前20个字符。现在,将文件指针放置在第21个字符。

syswrite 方法:

可以使用方法 syswrite 中的内容写入到一个文件中。需要打开该文件在写入模式使用方法 syswrite 时。
例如: 


#!/usr/bin/ruby

aFile = File.new("input.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
else
   puts "Unable to open file!"
end

这条语句将 “ABCDEF” 写入到文件中。

each_byte 方法:

这种方法属于类 File 。总是关联一个块方法each_byte。考虑下面的代码示例:: 


#!/usr/bin/ruby

aFile = File.new("input.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
   aFile.each_byte {|ch| putc ch; putc ?. }
else
   puts "Unable to open file!"
end

一个接一个字符传递变量ch,然后在屏幕上显示如下:


s. .a. .s.i.m.p.l.e. .t.e.x.t. .f.i.l.e. .f.o.r. .t.e.s.t.i.n.g. .p.u.r.p.o.s.e...
.
.

IO.readlines 方法:

类File 是 IO类的一个子类。类的IO也有一些方法可用于对文件进行操作。

IO类的方法之一是IO.readlines。此方法返回的内容文件行。下面的代码显示使用方法IO.readlines:


#!/usr/bin/ruby

arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]

在这段代码中,变量arr是一个数组。将文件 input.txt 的每一行,将数组arr中的元素。因此arr[0]将包含在第一行,而到达[1]将包含该文件的第二行。

IO.foreach 方法:

此方法还返回一行一行的输出。foreach和 readlines 方法之间的差异是 foreach方法可以带有块相关联,foreach不会返回一个数组。例如:


#!/usr/bin/ruby

IO.foreach("input.txt"){|block| puts block}

此代码将传递该文件的内容,测试可变块的行,然后,输出将被显示在屏幕上。

重命名和删除文件:

可以重命名和删除文件用Ruby以编程方式使用 rename 和 delete 方法。

下面的例子,重命名现有文件 test1.txt:


#!/usr/bin/ruby

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

下面的例子删除现有文件 test2.txt:


#!/usr/bin/ruby

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

文件模式和所有权:

使用chmod掩码的方法来改变模式或权限/访问的文件列表:

下面的例子改变现有的文件test.txt模式掩码值:


#!/usr/bin/ruby

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

以下的表可以帮助选择不同的面具为chmod方法:

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

文件查询:

下面的命令测试一个文件是否存在,然后再打开它:


#!/usr/bin/ruby

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

下面的命令查询文件是否是真是个文件:


#!/usr/bin/ruby

# This returns either true or false
File.file?( "text.txt" ) 

给定文件名是否为一个目录,下面的命令查找:


#!/usr/bin/ruby

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

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

下面的命令查找该文件是否可读,可写或可执行文件:


#!/usr/bin/ruby

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

下面的命令查找该文件是否有大小为零或不:


#!/usr/bin/ruby

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

下面的命令返回的文件大小:


#!/usr/bin/ruby

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

可以使用下面的命令找出一种类型的文件:


#!/usr/bin/ruby

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

 ftype 方法识别的文件类型返回下列之一: file, directory, characterSpecial, blockSpecial, fifo, link, socket 或 unknown.

下面的命令可以用来发现当一个文件被创建,修改或上次访问:


#!/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

Ruby中的目录:

所有文件都包含在不同的目录,Ruby也没有处理这些问题。鉴于文件中类处理文件,使用目录处理Dir类。

通过目录导航:

要改变一个Ruby程序的目录内,可使用Dir.chdir如下。这个例子改变当前目录 /usr/bin.


Dir.chdir("/usr/bin")

可以使用 Dir.pwd 找出当前目录是什么:


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

得到一个使用一个特定的目录内的文件和目录列表,使用 Dir.entries:


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

Dir.entries 返回一个数组的指定目录内的所有项目。Dir.foreach 提供了相同的功能:


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

更简捷的方法获取目录列表利用 Dir 类数组的方法:


Dir["/usr/bin/*"]

创建一个目录:

可以用 Dir.mkdir,来创建目录:


Dir.mkdir("mynewdir")

还可以设置一个新的目录权限(不是一个已经存在的)用mkdir:

注: 掩码755设置权限所有者,组表示 [所有人] 类似于 rwxr-xr-x , r = read, w = write, and x = execute.


Dir.mkdir( "mynewdir", 755 )

删除目录:

可用 Dir.delete 删除一个目录。Dir.unlink 和 Dir.rmdir 执行完全相同的功能,并提供了方便。


Dir.delete("testdir")

创建文件和临时目录:

临时文件是程序的执行过程中可能会产生短暂的,但不是永久存储的信息。

Dir.tmpdir 提供对当前系统的临时目录的路径,尽管该方法是默认不可用。为了使 Dir.tmpdir 必要使用需要 'tmpdir'.

可以使用 Dir.tmpdir 及 File.join,创建一个独立于平台的临时文件:


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)

此代码创建一个临时文件,写入数据,并删除它。 Ruby的标准库还包括一个程式库Tempfile ,它可以创建临时文件:


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

内置功能:

这里是Ruby的支持功能,处理文件和目录的完整列表:

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务