I/O处理 #
本地I/O #
目录 #
创建目录
不支持多级目录
unless Dir.exist? 'files'
Dir.mkdir 'files'
end
改变当前工作目录
Dir.chdir("/usr/bin")
遍历目录
Dir.foreach('/') do |entry|
puts entry
end
文件 #
Ruby 不支持 one/two/three
这样的多级文件,需要先切换目录。
打开文件
第一种方式
file = File.open(filename, 'w')
file.close()
第二种方式
File.open('test.txt', 'r') do |file|
# 处理文件
end
文件模式
- w 只写
- w+ 读写
- r 只读
- a 追加
- a+ 追加可读
读取文件
读取全部
File.open('test.txt', 'r') do |file|
puts "read: #{file.read}"
end
读取到数组中
lines = IO.readlines('test.txt')
puts "line: #{lines[0]}"
按行读取
IO.foreach('test.txt') { |block| puts "each: #{block}" }
写入文件
以下方法都需要自行追加换行
file.syswrite('hello world')
file.write('foobar')
file.print("world\n")
file.puts('bye')
判断文件是否存在
File.exist? 'files/test.txt'
File::directory?( "/usr/local/bin" )
是否可读
File.readable?( "test.txt" )
重命名和删除文件
File.rename( "test1.txt", "test2.txt" )
File.delete("text2.txt")
修改访问权限
file.chmod( 0755 )
网络I/O #
http #
require 'open-uri'
open('https://www.github.com') do |http|
html = http.read
puts html
end
Socket #
Server 端 #
require 'socket'
class Server
def connect
server = TCPServer.open(2000)
loop {
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime)
client.puts 'Closing the connection. Bye!'
client.close
end
}
end
end
Client 端 #
require 'socket'
class Client
def initialize(name)
@name = name
end
def connect
socket = TCPSocket.open('localhost', 2000)
while (line = socket.gets)
puts "#{@name} #{line.chop}"
end
socket.close
end
end