如何使用Ruby的文件方法将一个文件的内容复制到另一个文件?

Mit*_*ran 9 ruby

我想使用Ruby的文件方法将一个文件的内容复制到另一个文件.

如何使用文件方法使用简单的Ruby程序来实现?

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)

  • 只是评论`b`表示`binmode`([二进制文件模式](https://ruby-doc.org/core-2.2.0/IO.html#method-c-new-label-IO+Open+模式)). (2认同)

Vic*_*roz 8

作为预防措施,我建议使用缓冲区,除非你能保证整个文件总是适合内存:

    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)

  • 这几乎与`IO.copy_stream`方法重复.甚至不需要缓冲区,因为ruby内部使用`16*1024`(16Kb)缓冲区用于`IO.copy_stream`,[链接到创建此缓冲区的源代码中的内部函数,并在循环中读取和写入] (https://github.com/ruby/ruby/blob/f2d18484417fdc6e9ae4970fed7eda0de1027e91/io.c#L10692) (3认同)

Mit*_*ran 1

这是使用 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!

  • 您可能会解释“script = $0”的用途,同时防止读取大于内存的文件。 (3认同)