如何将文件内容复制到另一个文件?

时间:2011-05-14 23:39:05

标签: ruby file-io

基本上看来,我根本无法将一个文件的内容复制到另一个文件。这是我到目前为止的代码:

#!/usr/bin/ruby

Dir.chdir( "/mnt/Shared/minecraft-server/plugins/Permissions" )

flist = Dir.glob( "*" )

flist.each do |mod|
    mainperms = File::open( "AwesomeVille.yml" )
    if mod == "AwesomeVille.yml"
        puts "Shifting to next item..."
        shift
    else
        File::open( mod, "w" ) do |newperms|
            newperms << mainperms
        end
    end
    puts "Updated #{ mod } with the contents of #{ mainperms }."
end

3 个答案:

答案 0 :(得分:7)

为什么要将一个文件的内容复制到另一个文件?为什么不使用操作系统来复制文件,或者使用Ruby的内置FileUtils.copy_file

ri FileUtils.copy_file
FileUtils.copy_file

(from ruby core)
------------------------------------------------------------------------------
  copy_file(src, dest, preserve = false, dereference = true)

------------------------------------------------------------------------------

Copies file contents of src to dest. Both of src and
dest must be a path name.

更灵活/更强大的替代方法是使用Ruby的内置FileUtils.cp

ri FileUtils.cp
FileUtils.cp

(from ruby core)
------------------------------------------------------------------------------
  cp(src, dest, options = {})

------------------------------------------------------------------------------

Options: preserve noop verbose

Copies a file content src to dest.  If dest is a
directory, copies src to dest/src.

If src is a list of files, then dest must be a directory.

  FileUtils.cp 'eval.c', 'eval.c.org'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
  FileUtils.cp 'symlink', 'dest'   # copy content, "dest" is not a symlink

答案 1 :(得分:1)

这对我有用

IO.copy_stream mainperms, mod

§ copy_stream

答案 2 :(得分:0)

我意识到这不是完全认可的方式,但是

 IO.readlines(filename).join('') # join with an empty string because readlines includes its own newlines

将文件加载到字符串中,然后可以将其输出到newperms,就像它是一个字符串一样。目前无法正常工作的原因是您正在尝试将IO处理程序写入文件,并且IO处理程序不会按照您希望的方式转换为字符串。

但是,另一个修复可能是

 newperms << mainperms.read

另外,请确保在脚本退出之前关闭mainperms,因为如果不这样做,它可能会破坏。

希望这有帮助。