Mar*_*oda 18
有一个非常方便的方法IO#copy_stream method
- 看 - 输出ri copy_stream
用法示例:
File.open('src.txt') do |f|
f.puts 'Some text'
end
IO.copy_stream('src.txt', 'dest.txt')
Run Code Online (Sandbox Code Playgroud)
asc*_*iel 11
对于那些有兴趣,这里的的变化IO#copy_stream
,File#open + block
答案(S)(书对红宝石2.2.x以上,3年为时已晚).
copy = Tempfile.new
File.open(file, 'rb') do |input_stream|
File.open(copy, 'wb') do |output_stream|
IO.copy_stream(input_stream, output_stream)
end
end
Run Code Online (Sandbox Code Playgroud)
作为预防措施,我建议使用缓冲区,除非你能保证整个文件总是适合内存:
File.open("source", "rb") do |input|
File.open("target", "wb") do |output|
while buff = input.read(4096)
output.write(buff)
end
end
end
Run Code Online (Sandbox Code Playgroud)
这是使用 ruby 文件操作方法执行此操作的简单方法:
source_file, destination_file = ARGV
script = $0
input = File.open(source_file)
data_to_copy = input.read() # gather the data using read() method
puts "The source file is #{data_to_copy.length} bytes long"
output = File.open(destination_file, 'w')
output.write(data_to_copy) # write up the data using write() method
puts "File has been copied"
output.close()
input.close()
Run Code Online (Sandbox Code Playgroud)
您还可以用来File.exists?
检查文件是否存在。如果确实如此,这将返回布尔值 true!